简体   繁体   English

Laravel 5.2链接方法

[英]Laravel 5.2 chaining methods

I have two tables: 我有两个表:

organisations contains: organisations包含:

id   name   address   subscription_plan_id   .... other columns
--   ----   -------   --------------------
1    xyz    123 St    23

subscription_plans contains: subscription_plans包含:

id   name      cost    .... other columns
--   -------   -----
23   monthly   12.00

I have a class for each where I set up the following Eloquent relationships: 我为每个人建立了以下口才关系类:

Class Organisation : 班级Organisation

public function subscriptionPlan()
{
    return $this->hasOne(SubscriptionPlan::class, 'id', 'subscription_plan_id');
}

Class SubscriptionPlan : 班级SubscriptionPlan

public function subscriptionPlan()
{
    return $this->belongsTo(SubscriptionPlan::class, 'subscription_plan_id', 'id');
}

In my controller I want to create a collection with selected columns from each table, using the Eloquent relationships, but I have not managed to do this without essentially using SQL... I extract each collection with the following commands: 在我的控制器中,我想使用Eloquent关系,使用每个表中的选定列创建一个集合,但是在没有本质上使用SQL的情况下,我没有设法做到这一点...我使用以下命令提取每个集合:

$subscriptionPlans = SubscriptionPlan::all();

$organisations = Organisation::all();

How do I extract one collection chaining the relationships and nominating the columns I want? 如何提取链接关系并指定所需列的一个集合?

Something like the blow (which does not work): 像是打击(不起作用):

$organisationsAndPlans = Organisation::all()
         ->subscriptionPlan()
         ->get('organisations.col1', 'subscription_plans.col3');

You can simply eager load the relationship by using the with method on the Illuminate\\Database\\Query\\Builder class. 您可以通过在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');

This will allow you to choose what columns you want to select from the relationship. 这将允许您选择要从关系中选择的列。

$organisationsAndPlans = Organisation::select('table1.col1','table2.col2')
->with('subscriptionPlan')
->join(function($join){
       $join->on('table2.ref_id','=', 'table1.id'});
->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM