簡體   English   中英

Laravel雄辯的一對多關系

[英]Laravel eloquent One to Many relation

我無法弄清楚如何使用Eloquent定義一對多關系。

這是桌子

----------- Country -----------
id | title | code | currency_code

----------- Currency Code --------
id | name | symbol | code 

一個國家可能有許多貨幣。

因此,我將模型定義如下

class Country extends Model
{
    public function currencies()
    {
        $this->hasMany('App\Models\Currency', 'code', 'currency_code');
    }

}

貨幣模型很簡單

class Currency extends Model
{


}

我正在選擇這樣的國家

   return Country::all('country_id AS value', 'title_ru AS title','currency_code')
   ->sortBy('value');

但是當我嘗試訪問貨幣時它返回null

我的定義有什么問題,我將不勝感激。

謝謝

您可以按照以下代碼設置模型:

國家模型:

class Country extends Model
{
    protected $table = 'country';
    protected $primaryKey = 'id';

    public function currency(){
        return $this->hasMany(App\Models\Currency', 'code', 'currency_code');
    }

}

貨幣模型:

class Currency extends Model
{
    protected $table = 'currency';
    protected $primaryKey = 'id';

    public function country(){
        return $this->belongTo('App\Models\Country', 'code');
    }

}

然后,如果您想獲取特定國家/地區數據(使用貨幣),則可以使用以下方法:

$data = County::where('id','=',$id)->with('currency')->first();

或者,如果您想獲得所有可以使用的東西:

$data = County::with('currency')->get();

您應該嘗試這樣:

國家模型

class Country extends Model
{
    public function currencies()
    {
        $this->belongsTo('App\Models\Currency', 'currency_code');
    }

}

貨幣模型

class Currency extends Model
{
    public function country()
    {
        $this->belongsTo('App\Models\Country');
    }

}

暫無
暫無

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

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