簡體   English   中英

Laravel 5.2鏈接方法

[英]Laravel 5.2 chaining methods

我有兩個表:

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

我為每個人建立了以下口才關系類:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM