【问题标题】:Eloquent One To Many issue雄辩的一对多问题
【发布时间】:2016-07-20 15:43:56
【问题描述】:

我有一个与标题相关的问题。 所以我有这个模型(如果你需要告诉我,我有更多的代码和模型)

客户模式

protected $table = 'cliente';
protected $primaryKey = 'id_cliente';
public $timestamps = false;

public function seguroCarro()
{
    return $this->hasMany('App\SeguroCarro', 'id_seguro_carro');
}

SeguroCarro 模型

protected $table = 'seguro_carro';
protected $primaryKey = 'id_seguro_carro';
public $timestamps = false;

public function cliente()
{
    return $this->belongsTo('App\Cliente', 'id_cliente');
}

问题:

这个Cliente::find(1)->seguroCarro 得到 seguro_carro 的 id 为 1 而不是 id_cliente 1 但这个 SeguroCarro::all()->where('id_cliente',Auth::user()->cliente->id_cliente) 得到我需要的 3 行 seguro_carro

我不明白为什么会这样,但我想知道为什么

注意: 这个Cliente::find(1)->seguroCarro 是你们我的代码Auth::user()->cliente->seguroCarro [my Auth::user()->cliente has the id 1]的缩写]

img of rows on seguro_carro table

谢谢你们的时间

【问题讨论】:

  • 试试这个:Auth::user()->seguroCarro()->get()
  • 我尝试 Auth::user()->seguroCarro()->get(), Auth::user()->cliente()->seguroCarro()->get() ,没有我正在使用 SeguroCarro::all()->where('id_cliente',Auth::user()->cliente->id_cliente) 就像我说的那样,直到有更好的方法

标签: laravel orm eloquent laravel-5.2


【解决方案1】:

App\Cliente 模型上的关系指定了错误的键。 hasOne/hasMany 关系的第二个参数是相关对象上的外键字段的名称。在这种情况下,相关对象 (App\SeguroCarro) 上的外键是 id_cliente,而不是 id_seguro_carro

您当前的关系将获得seguro_carro 记录where seguro_carro.id_seguro_carro = cliente.id_cliente,这不是您想要的。

关系应该改为:

public function seguroCarro()
{
    return $this->hasMany('App\SeguroCarro', 'id_cliente');
}

这将获得seguro_carro 记录where seguro_carro.id_cliente = cliente.id_cliente,这是您想要的。

App\SeguroCarro 上的 belongsTo 关系是正确的。

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2012-10-08
    • 2018-10-27
    • 2014-10-08
    • 2014-05-23
    相关资源
    最近更新 更多