問題描述
我正在嘗試使用 Eloquent 在數據庫種子期間執行以下查詢:
I'm trying to use Eloquent to perform the following query during a database seed:
SELECT
*
FROM
customers
LEFT JOIN
orders
ON customers.id = orders.customer_id
WHERE
orders.customer_id IS NULL
這是我在 Eloquent 中的實現:
And here is my implementation in Eloquent:
$c = Customer::leftJoin('orders', function($join) {
$join->on('customers.id', '=', 'orders.customer_id');
})
->whereNull('orders.customer_id')
->first();
第一個查詢總是返回完整的結果,而 Eloquent 的等效項總是返回空元素,除了 customers
的 email
和 phone
字段> 桌子.我無法解釋這一點,因為 Customers
和 Orders
模型都是工匠生成的骨架.
Whereas the first query always returns full results, the Eloquent equivalent always returns empty elements for everything but the email
and phone
fields of the customers
table. I'm at a loss to explain this since the Customers
and Orders
models are both artisan generated skeletons.
例如:
class Customer extends Eloquent {
// Add your validation rules here
public static $rules = [
// 'title' => 'required'
];
// Don't forget to fill this array
protected $fillable = [];
}
這是當我 dd() 對種子(最初由 Faker 生成)第一個 Eloquent 查詢時輸出的數組:
Here is the array that is output when I dd() the first Eloquent query on a seed (generated originally by Faker):
protected $original =>
array(25) {
'id' =>
NULL
'first_name' =>
NULL
'last_name' =>
NULL
'email' =>
string(24) "luther.braun@example.org"
'phone' =>
string(17) "642.150.9176x5684"
'address1' =>
NULL
'address2' =>
NULL
'city' =>
NULL
'state' =>
NULL
'county' =>
NULL
'district' =>
NULL
'postal_code' =>
NULL
'country' =>
NULL
'notes' =>
NULL
'created_at' =>
NULL
'updated_at' =>
NULL
'customer_id' =>
NULL
'total' =>
NULL
}
推薦答案
這可以通過指定特定表中所需的特定列名來解決,如下所示:
This can be resolved by specifying the specific column names desired from the specific table like so:
$c = Customer::leftJoin('orders', function($join) {
$join->on('customers.id', '=', 'orders.customer_id');
})
->whereNull('orders.customer_id')
->first([
'customers.id',
'customers.first_name',
'customers.last_name',
'customers.email',
'customers.phone',
'customers.address1',
'customers.address2',
'customers.city',
'customers.state',
'customers.county',
'customers.district',
'customers.postal_code',
'customers.country'
]);
這篇關于Laravel Eloquent LEFT JOIN WHERE NULL的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!