問題描述
我有一個(gè)與 這個(gè)不同的問題.場景相同,但我需要對結(jié)果進(jìn)行更多過濾.
I have a different problem from this. The scenario is same but I am in need of more filtration of the results.
讓我解釋一下.
考慮我有 2 張桌子
車輛
id
name
staff_id
distance
mileage
員工
id
name
designation
我只想從兩個(gè)表(模型)中選擇 id
和 name
.Vehicle Model 包含與 Staff 模型的 belongsTo
關(guān)系.
I want to select only id
and name
from both tables(Models).
The Vehicle Model contain a belongsTo
relation to Staff model.
class Vehicle extends Model
{
public function staff()
{
return $this->belongsTo('AppStaff','staff_id');
}
}
我加入使用這個(gè)
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get();
當(dāng)我像這樣將字段放在 ->get()
中時(shí)
When I put fields in ->get()
like this
->get(['id','name'])
它過濾了vehicle
表,但沒有產(chǎn)生Staff表的結(jié)果.
it filters the vehicle
table but produce no result of Staff table.
有什么想法嗎?
推薦答案
終于找到了..在 ->get()
中,你必須像這樣輸入 'staff_id'
Finally found it..
In the ->get()
you have to put the 'staff_id' like this
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get(['id','name','staff_id']);
由于我沒有使用 staff_id
,它無法執(zhí)行連接,因此沒有顯示人員表字段.
Since I didn't take the staff_id
, it couldn't perform the join and hence staff table fields were not shown.
這篇關(guān)于如何從連接表中選擇列:laravel eloquent的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!