Laravel查询子查询

时间:2015-04-01 14:08:56

标签: php sql laravel-4

例如,我有2个查询:

1

$q = SomeContent::select('somecontent_id')
    ->where('slug', Request::segment(2))
    ->where('something', $something)
    ->first();

2

$req = SomeContent::select('slug')
    ->where('something', $anothersomething)
    ->where('somecontent_id', $q->somecontent_id)
    ->first();

如果可能的话,如何在laravel的查询构建器中将这些作为一个查询合并在一起?我找不到很多关于在where语句中使用choose语句的信息。

2 个答案:

答案 0 :(得分:1)

你可以union将它们放在一起,比如

// The query builder also provides a quick way to "union" two queries together:

$q = SomeContent::select('somecontent_id')
    ->where('slug', Request::segment(2))
    ->where('something', $something);

$req = SomeContent::select('slug')
    ->where('something', $anothersomething)
    ->where('somecontent_id', $q->somecontent_id)
    ->union($q)->get();

答案 1 :(得分:1)

你也可以使用orWhere函数

$q = SomeContent::select('somecontent_id')
      ->where('slug', Request::segment(2))
       ->where('something', $something)
        ->orWhere(function($query)
        {
            $query->where('something', $anothersomething)
          ->where('somecontent_id', $q->somecontent_id)
           ->union($q)->get();
        })
        ->get();