【问题标题】:laravel 5 - Eloquent relationslaravel 5 - 雄辩的关系
【发布时间】:2015-10-22 09:51:52
【问题描述】:

我有一个名为 plates 的迁移表。

$table->increments('id');
$table->integer('supplier_id')->unsigned();
$table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('cascade')->onUpdate('cascade');

还有一个模型叫做Plates

 public function supplier()
{
    return $this->belongsTo('App\Models\Suppliers','supplier_id');
}

还有一个模型供应商模型

 public function plates()
        {
            return $this->hasOne('App\Models\Plates');
        }

当我检查与做这种事情的路线中的关系时。

 $storage = Suppliers::find(1);
   $att = $storage->plates;

   dd($att);

它只是不起作用。但反之亦然。我不确定我做错了什么。我检查了文档并做了无数其他尝试,但我再也无法理解了。

这是不断弹出的error

【问题讨论】:

  • return $this->hasOne('App\Models\Plates', 'supplier_id');
  • @Daan 嗯,成功了!非常感谢。但我很好奇为什么会发生这种情况。我的命名约定有问题吗?我做事的方式不对吗?
  • 你的模型叫做Suppliers,所以它会自动认为你的外键叫做suppliers_id,除非你另外指定。
  • 我建议你用一个单数名词来命名你的模型:它会在现在和将来为你省去很多麻烦。

标签: php laravel


【解决方案1】:

您必须在 Supplier Model 的plates 函数中添加参数,您以复数形式创建了模型,Suppliers,因此它会尝试找到关键的suppliers_id

  public function plates()
  {
      return $this->hasOne('App\Models\Plates', 'supplier_id');
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2015-12-17
    • 2017-08-22
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多