Laravel mysql查询翻译

时间:2014-09-17 15:59:59

标签: laravel translation

我需要帮助将其翻译成Laravel。感谢。

SELECT * FROM benefit 
WHERE id 
NOT IN ( 
       SELECT benefit_id 
       FROM benefit_aquired 
       WHERE benefit_aquired.user_id = 6 
       )

2 个答案:

答案 0 :(得分:1)

假设您在Benefit型号上调用它:

Benefit::whereNotIn('id', function ($q) use ($userId) {
  $q->from('benefit_acquired')
     ->where('user_id', $userId)
     ->select('benefit_id');
})->get();

这将为您提供与您粘贴的完全相同的查询。

对于非雄辩的查询,它是一样的:

DB::table('benefit')->whereNotIn('id', function ($q) use ($userId) {
  $q->from('benefit_acquired')
     ->where('user_id', $userId)
     ->select('benefit_id');
})->get();

答案 1 :(得分:-1)

如果查询太难转换为Laravel,您可以始终使用DB :: SELECT。例如,在我的一个模型中,我有一个这样的方法:

 /**
* Get all predictions spent so far
* @param int $userId
* @return string
*/
public function getAllSpentPredictions($userId)
{
return DB::select("SELECT `predictions`.name , sum(ex.expenseValue) as value
FROM `predictions`
INNER JOIN (SELECT prediction_id, sum(value) as expenseValue from expenses GROUP BY prediction_id) ex
ON `predictions`.id = ex.prediction_id
WHERE `predictions` .tablet_id in (select id from tablets where user_id = $userId)
group by name
ORDER BY value DESC
;");
}

正如您所看到的,我的SQL查询也有点复杂,所以我只使用了DB :: select。