【问题标题】:laravel ORM relations : using Conditions on With Joinslaravel ORM 关系:在 With Joins 上使用条件
【发布时间】:2016-12-13 16:56:44
【问题描述】:

我正在尝试使用 ORM 关系连接两个表 post 和 comment,

$posts = Post::with('comments')->get(); 

使用with 加入表格时如何在 cmets 上使用条件?

我可以使用 whereHas like

$posts = Post::whereHas('comments', function ($query) {
    if(isset($_GET['title']))
    $query->where('title', $_GET['title']);
})->get();

但是当我使用whereHas 时,如果结果中没有任何评论,我将不会收到帖子

基本上我想在右表上使用带条件的左连接

【问题讨论】:

  • 您能否发布您想要的Sql 查询,以便我们轻松理解问题..

标签: php laravel orm laravel-5.2


【解决方案1】:

您可以像这样将闭包传递给with() 方法:

$posts = Post::with(['comments' => function($q) {
    $q->where('column', '=', 'value'); // Put conditions here
}])->get();

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    你需要使用闭包:

    $title = $_GET['title'];
    $posts = Post::whereHas('comments', function ($query) use ($title) {
        if(!empty($title)) {
            $query->where('title', $_GET['title']);
        }
    })->get();
    

    参考:

    In PHP 5.3.0, what is the function "use" identifier?

    【讨论】:

      猜你喜欢
      • 2017-04-30
      • 1970-01-01
      • 2016-03-27
      • 2015-07-20
      • 1970-01-01
      • 2018-09-08
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多