【问题标题】:can't retrieve distant data with hasManyThrough method无法使用 hasManyThrough 方法检索远程数据
【发布时间】:2016-10-24 18:42:27
【问题描述】:

为了举例,我有这个设置:

item_model
    id - integer
    name - string

collected_item
    id - integer
    model_id - integer


posts
    id - integer
    collected_item_id - integer
    title - string

我想通过collected_item模型检索关于item_model的所有帖子。

所以我在 item_model 中这样设置关系:

public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\Collected_item');
    }

但是我如何检索帖子?由于我正在按名称寻找模型,因此我尝试这样无济于事:

$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts();

$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts()->get();

返回错误:

调用未定义的方法 Illuminate\Database\Query\Builder::posts()

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    尝试“with”方法..

    $posts = Item_model::with('posts')->where('model_name', 'LIKE', $q . '%')->get();
    

    要仅获取帖子存在的 item_models,请使用“has”方法

    $posts = Item_model::has('posts')->where('model_name', 'LIKE', $q . '%')->get();
    

    【讨论】:

    • 它有点工作,但这种方式检索所有 item_models,无论它们是否有相关帖子。我只需要检索帖子而不是模型。
    • 如果你只想要有帖子的 item_models,你必须使用 Has 方法,像这样.. $posts = Item_model::has('posts')->where('model_name', ' LIKE', $q . '%')->get();
    • 不,我想要的是帖子而不是模型,根据 laravel 文档,这应该可以通过 hasManyThrough 实现。但它不起作用。
    • 我们没有你的模型设置,但也许你也必须在 Posts 模型中为 ItemModel 设置相反的实现.. 并得到它: $posts = Posts::has('itemModel') ->where('model_name', 'LIKE', $q . '%')->get();
    • 我不这么认为,因为它是通过collected_item有很多相关帖子的模型而不是相反的。
    【解决方案2】:

    我认为你必须在调用 get 之前声明方法的名称

    Item_model::with('posts')->get();

    【讨论】:

    • 它有点工作,但这种方式检索所有 item_models,无论它们是否有相关帖子。我只需要检索帖子而不是模型。
    • 你的 laravel 版本是什么?
    • 版本 5.1.28 (LTS)
    • ->where('model_name', 'LIKE', '%'. $q . '%') 也试试在前面加 %,告诉我
    • 为什么?这将只检索更多模型,其中术语在两个通配符之间而不是帖子
    【解决方案3】:

    我终于让它工作了。这是Item_model中的正确关系

    public function posts()
        {
            return $this->hasManyThrough('App\Post', 'App\Collected_item', 'model_id', 'collected_item_id', 'id' );
        }
    

    其中第三个参数是中间模型中的外键,第四个是 Post 模型中的外键,第五个是本地 (item_model) 键。

    在那之后,我不必预先加载我可以做的帖子:

    $item= Item_model::find(220); (an item which I know has related posts)
    
    $posts = $item->posts;
    
    dd($posts);
    

    这会返回帖子,因此您不必像其他建议的那样必须先加载它们,hasManyThrough 方法负责检索帖子。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多