donglin6109 2016-12-14 20:45
浏览 80

laravel ORM关系:left在右表中加入类似查询和可选条件

i have two table, tutorial:id,title and tutorial_tags:id,tutorial_id,title

the relation in tutorial model is defined like this :

function TutorialTag(){
        return $this->hasMany('App\TutorialTag');
    }

i want to left join tutorials with tutorial_tags , like (please ignore syntax errors):

select tutorials.* , tutorial_tags.* from `tutorials` left Join 
`tuotrial_tags` ON tutorials.id = tutorial_tags.tutorial_id 

but i want to be able to use Conditions on tutorial_tags in case user want to search a particular tags:

select tutorials.* , tutorial_tags.* from `tutorials` left Join 
`tuotrial_tags` ON tutorials.id = tutorial_tags.tutorial_id 
where tutorial_tags.title = 'ABC'

if i use whereHas like this :

    $tutorials = Tutorial::whereHas('TutorialTag',function ($query){
        if(isset($_GET['tag']))
            $query->where('title',$_GET['tag']);
    })->get();

i dont get tutorials that are without any tag, basically it works like inner Join.

and if i use with :

    $tutorials = Tutorial::with(['TutorialTag'=>function($query){
        if(isset($_GET['tag']))
            $query->where('title',$_GET['tag']);
    }])->get();

then ill get two separate queries with no effect on eachother, basically the where condition on tutorial_tags has no effect on tutorials and i get all the tutorials even the ones without sreached tag, here is the query log :

Array
(
    [0] => Array
        (
            [query] => select * from `tutorials`
            [bindings] => Array
                (
                )

            [time] => 0
        )

    [1] => Array
        (
            [query] => select * from `tutorial_tags` where `tutorial_tags`.`tutorial_id` in (?, ?, ?) and `title` = ?
            [bindings] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => ABC
                )

            [time] => 2
        )

)

how can i get left Join like query with optional condition on the right table

  • 写回答

2条回答 默认 最新

  • duan19805 2016-12-15 05:16
    关注

    This is not an efficient sql query, but you can solve the issue with laravel collections and an extra query.

    Grab all the intersections:

    $tutorials1 = Tutorial::whereHas('TutorialTag',function ($query){
        if(isset($_GET['tag']))
            $query->where('title',$_GET['tag']);
    })->get();
    

    Grab the rest:

    $tutorials2 = Tutorial::doesntHave('TutorialTag')->get();
    

    Merge both collections:

    $tutorials = $tutorials1->merge($tutorials2);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条