【问题标题】:Laravel eloquent One to Many relationLaravel 雄辩的一对多关系
【发布时间】:2018-10-27 16:40:21
【问题描述】:

我不知道如何使用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

我的定义有什么问题,我将不胜感激。

谢谢

【问题讨论】:

  • 文档提供了很好的示例,请阅读它们。 laravel.com/docs/5.5/eloquent-relationships#one-to-many
  • @LukeRamsden 我已经阅读了好几遍文档,但它不起作用
  • 您可能需要在查询中预先加载货币。检查文档并查看适用的内容
  • 您如何/在哪里访问currencies

标签: php database laravel orm eloquent


【解决方案1】:

你可以像下面的代码那样设置你的模型:

国家模式:

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

【讨论】:

    【解决方案2】:

    你应该试试这个:

    国家模式

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

    【讨论】:

    • 感谢您的回答,但我收到以下错误select * from cdr_currencies` 其中cdr_currencies.id 为空`
    • @bxfvgekd:请给我完整的错误,我会尽力解决这个问题
    猜你喜欢
    • 2012-10-08
    • 2018-11-14
    • 2015-07-01
    • 2019-03-10
    • 2016-11-03
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多