jeudi 31 décembre 2015

Laravel 5.2 chaining methods

Happy new year! I am new to Laravel 5 and I am playing with it for the last time in 2015, and I am stuck.

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire