【问题标题】:带有多个“with”语句的 Laravel 查询
【发布时间】:2022-01-20 12:12:49
【问题描述】:

我不确定是否有这样做的方法,但我想在我的查询中将 where 子句添加到第二个 with 但它不起作用。它只是返回所有选票,就好像条件不存在一样。任何帮助将不胜感激。

public function PostId($request)
{
    $post_id = $request->post_id;
    $user_id = auth('api')->user();

    $post = Post::with('categories')
        ->where('id', $post_id)
        ->with('votes')
        ->where('user_id', $user_id->id)
        ->first();

    return $post;
}

【问题讨论】:

  • 您只需将它们放入一个数组中。 with(['categories', 'votes'])
  • 您是要限制关系的急切加载,还是要根据存在关系的条件过滤Post
  • @Second2None 这不太正确。如果您想为votes 关系添加条件,请使用带有回调的数组:with(['votes' => function ($subQuery) use ($user_id) { return $subQuery->where('user_id', $user_id->id); }])。旁注,$user_id 是一个错误的变量名,因为它是实际的 User 实例,而不仅仅是 id。更改为$user_id = auth('api')->user()->id,或$user = auth('api')->user(),然后更改为$user->id,等等。
  • 感谢您的回复。我已经更新了变量名并实现了回调,但它返回了一个空对象。没有错误。
  • 只要你最终到达那里......文档参考:laravel.com/docs/8.x/…......祝你好运,玩得开心,享受 Laravel

标签: sql laravel eloquent


【解决方案1】:

您需要在 with 语句中使用闭包。

另外,我建议您使用findOrFail() 而不是where 条件查询。因此,如果您在请求中传递了错误的post_id,则会引发异常 404。

实现您想要的更好的方法可能是:

public function PostId($request)
{
    $post = Post::with(['categories', 'votes' => function($query){
           $query->where('user_id', auth('api')->user()->id);
        })
        ->findOrFail($request->post_id);

    return $post;
}

【讨论】:

    【解决方案2】:
    $post = Post::find($post_id) // Find method will return only first record. no need to call ->first() explicitly.
        ->with([
            'categories',
            'votes'
        ])
    

    对于->where('user_id', $user_id->id),您无需在此处执行,因为您已经定义了关系“投票”。

    Class Post
    {
        public function votes()
        {
            return $this->hasMany(Vote::class)->where('user_id', $this->user_id); // You can have the where condition here assuming you have user id field present in the Post model. Else you can keep it as below in your query
        }
    }
    

    在运行时查询中使用用户 ID

    $post = Post::find($post_id)
        ->with([
            'categories',
            'votes' => function($query) use($user_id) {
                $query->where('user_id', $user_id->id);
            }
        ])
    
    
    

    【讨论】:

    • with 返回一个 eloquent builder,而不是结果 ... find 运行一个查询并返回 Model 然后 with 启动一个新的 eloquent builder,然后最终需要执行查询做任何事情[您需要更改这 2 个方法调用的顺序]...当使用急切加载新的非现有模型实例时,您不能将 where 条件添加到模型本身的关系方法中调用关系方法,而不是现有的(它没有属性)$this->user_id 在这种情况下将是null
    猜你喜欢
    • 2012-01-28
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2010-12-18
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多