简体   繁体   中英

Laravel 5.2 chaining methods

I have two tables:

organisations contains:

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

subscription_plans contains:

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 :

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

Class 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:

$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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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