【问题标题】:HasMany with belongsToMany relationshipHasMany 与 belongsToMany 关系
【发布时间】:2014-12-30 08:40:39
【问题描述】:

我有 3 个模型:PersonsEventsFiles。一个Persons 可以有很多Events,很多Events 可以有很多Files

| persons |
-----------
id
name


| events |
----------
id
person_id
name


| event_file |
--------------
id
event_id
file_id


| files |
---------
id
name

Persons 模型中我有这种关系:

public function events()
{
    return $this->hasMany('Events', 'person_id');
}

Events 模型中:

public function files()
{
    return $this->belongsToMany('Files', 'event_file', 'event_id', 'file_id');
}

是否可以在PersonsFiles 之间直接创建关系,转换为:

$files = Person::find($id)->events->files;
// OR
$files = Person::find($id)->files;

谢谢!

【问题讨论】:

  • 不,使用内置方法是不可能的。

标签: database laravel laravel-4 eloquent relationship


【解决方案1】:

就像评论中一样,用 Eloquent 的内置方法建立这种关系是不可能的。以下是使用一些技巧获得files 的方法:

Person::with(['events.files' => function ($q) use (&$files) {
  $files = $q->get()->unique();
}])->find($id);

然后:

$files; // collection of files related to the Person through collection of his events

请注意,此代码将运行额外的查询来获取文件,因此在上面的示例中:

1 fetch Person
2 fetch Events related to Person
3 fetch Files related to all the Events
4 again fetch Files related to all the Events

【讨论】:

    【解决方案2】:

    您可以使用“hasManyThrough”。 在下面的示例中,您可以看到我想通过用户获取帖子。就像你想通过事件获取文件一样。

    class Country extends Eloquent {
    
        public function posts()
        {
            return $this->hasManyThrough('Post', 'User');
        }
    
    }
    

    你会调用为:

    $country->posts;
    

    或者,如你所愿:

    Person:find(1)->files;
    

    如果你想要更好的解释,请点击 Laravel 自己页面的链接: http://laravel.com/docs/4.2/eloquent#has-many-through

    【讨论】:

    • 不,hasManyThrough 不适用于 belongsToMany
    • 我不明白你的意思。它不是“与”,而是替换。这样使用有问题吗?我现在无法测试它。
    • 是的,它不适用于级联以外的关系,即。 A hasMany B, B hasMany C。我根本不是在谈论with 方法。
    • 哦,抱歉误导了你。不是在谈论“with”方法,而是在谈论belongsToMany。我只是坚持他的要求,而且,我真的错了。我只是通过事件给他文件,而不是事件。
    • 克劳斯,你没有明白我的意思。你不能按照你的建议去做。试试看,你就会知道我在说什么。
    【解决方案3】:

    怎么样

    Person::where('id',$id)->with('events')->with('events.files')->get();
    

    ?急切地加载

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 2021-03-22
      • 1970-01-01
      • 2018-01-03
      • 2021-10-07
      • 2022-01-16
      • 1970-01-01
      • 2016-07-12
      • 2017-07-25
      相关资源
      最近更新 更多