我有两个表:
organisations
包含:
id name address subscription_plan_id .... other columns
-- ---- ------- --------------------
1 xyz 123 St 23
subscription_plans
包含:
id name cost .... other columns
-- ------- -----
23 monthly 12.00
我为每个人都开设了一个课程,在那里我建立了以下Eloquent关系:
Organisation
:类
public function subscriptionPlan()
{
return $this->hasOne(SubscriptionPlan::class, 'id', 'subscription_plan_id');
}
SubscriptionPlan
:类
public function subscriptionPlan()
{
return $this->belongsTo(SubscriptionPlan::class, 'subscription_plan_id', 'id');
}
在我的控制器中,我想使用Eloquent关系创建一个集合,其中包含每个表中选定的列,但如果不使用SQL,我就无法做到这一点。。。我用以下命令提取每个集合:
$subscriptionPlans = SubscriptionPlan::all();
$organisations = Organisation::all();
如何提取一个链接关系并指定我想要的列的集合?
类似打击的东西(不起作用):
$organisationsAndPlans = Organisation::all()
->subscriptionPlan()
->get('organisations.col1', 'subscription_plans.col3');
您只需在Illuminate'Database'Query'Builder
类上使用with
方法即可快速加载关系。
Organisation::with([
'subscriptionPlan' => function($query) {
// Here you have to select the key that is being
// used by the relationship no matter what.
return $query->select('id', 'col2');
}
])->get('col1');
这将允许您选择要从关系中选择的列。
$organisationsAndPlans = Organisation::select('table1.col1','table2.col2')
->with('subscriptionPlan')
->join(function($join){
$join->on('table2.ref_id','=', 'table1.id'});
->get();