【问题标题】:hasManyThrough Laravel not workinghasManyThrough Laravel 不工作
【发布时间】:2018-07-22 18:46:30
【问题描述】:

鉴于下一个模型并使用 Laravel 5.2:

条目

  • 身份证

属性

  • entry_id
  • asset_uuid

资产

  • uuid

  1. 一个条目有很多属性
  2. 一个属性有一个资产
  3. 资产有很多属性

我想在 Entry 和 Asset 之间建立关系,但我无法使用 HasManyThrough 来实现,因为“属性具有一项资产”。这里是当前的关系:

入门模式

public function attributes()
{
    return $this->hasMany(EntryAttribute::class);
}

属性模型

public function asset()
{
    return $this->hasOne(Asset::class, 'uuid', 'asset_uuid');
}

资产模型

public function attribute()
{
    return $this->hasMany(EntryAttribute::class, 'asset_uuid', 'uuid');
}

关于如何进行资产关系的任何想法,例如:

$entry->assets()

提前致谢。

【问题讨论】:

  • 请提供关系代码

标签: php laravel eloquent laravel-5.2 has-many-through


【解决方案1】:

您可以在Entry 类中使用hasManyThrough,如下所示:

public function assets(){
    return $this->hasManyThrough(
        Asset::CLASS,
        EntryAttribute::CLASS,
        'entry_id', // Foreign key of your attribute table
        'asset_uuid', // Foreign key of your asset table
        'id', // Local id in your entry table
        'uuid', // Local id in your entry attribute table
    );
}

欲了解更多信息:https://laravel.com/docs/5.5/eloquent-relationships

【讨论】:

  • hasManyThrough 在较新的 Laravel 版本中发生了变化,并允许你说的参数。我在 Laravel 5.2 上,我只能设置 3 个键,而不是你指定的 4 个
  • @suarsenegger 您可以将条目表的local id 更改为id 或更新为5.5
猜你喜欢
  • 2016-12-28
  • 2018-09-25
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多