Laravel 将sql转换为雄辩的
我正在尝试用eloquent编写一个self-join,这里是SQLLaravel 将sql转换为雄辩的,laravel,eloquent,laravel-5,Laravel,Eloquent,Laravel 5,我正在尝试用eloquent编写一个self-join,这里是SQL SELECT t2.id FROM products t1, products t2 WHERE t1.id = 1 AND t2.id != 1 AND (t1.color_id = t2.color_id OR t1.process_id = t2.process_id OR t1.length_id = t2.length_id OR t1.size_id = t2.size_id OR t1.height_id
SELECT t2.id FROM products t1, products t2
WHERE t1.id = 1
AND t2.id != 1
AND (t1.color_id = t2.color_id
OR t1.process_id = t2.process_id
OR t1.length_id = t2.length_id
OR t1.size_id = t2.size_id
OR t1.height_id = t2.height_id)
ORDER BY rand() LIMIT 10
以下是我在《雄辩》中的观点:
Product::join('products AS t2', 'products.id', '=', 't2.id')
->select('t2.id')
->where('products.id', 1)
->where('t2.id', '!=', 1)
->where(function($query){
$query->where('products.color_id', '=', 't2.color_id')
->orWhere('products.process_id', '=', 't2.process_id')
->orWhere('products.length_id', '=', 't2.length_id')
->orWhere('products.size_id', '=', 't2.size_id')
->orWhere('products.height_id', '=', 't2.height_id');
})
->get();
我还没有给雄辩添加顺序和限制——只是想先得到一些结果
Elotent的问题是它产生了0个结果,我的sql提供了我期望的结果,我哪里出了问题
编辑
我已将我的查询修改为:
Product::join('products AS t2', 'products.id', '=', 't2.id')
->select('t2.id')
->where(function($query){
$query->where('products.color_id', '=', 't2.color_id')
->orWhere('products.process_id', '=', 't2.process_id')
->orWhere('products.length_id', '=', 't2.length_id')
->orWhere('products.size_id', '=', 't2.size_id')
->orWhere('products.height_id', '=', 't2.height_id');
})
->get();
但结果仍然是0
编辑2
以下是正在运行的sql语句:
select
`t2`.`id`
from
`products` inner join `products` as `t2`
on
`products`.`id` = `t2`.`id`
where (
`products`.`look_color_id` = ? or
`products`.`process_id` = ? or
`products`.`length_id` = ? or
`products`.`size_id` = ? or
`products`.`height_id` = ?
)
我在查询中输入了一些错误,Laravel编写了整个查询,然后调试它:)。问题出在
->where('products.id',1)
,我想你忘记了等号。谢谢,但它仍然不起作用。另一个问题出在join中,因为你加入p.id=t.id
,然后写下这样的条件p.id=1和t.id 1
,它总是假的,在你最初的查询中你没有这个连接。所以,请注意连接两个相同的表。@Jzef Duc在Laravel中的where条件中不必使用等号。它是可选的:)获取最后一个查询:$querys=DB::getQueryLog();回音结束($查询)代码>这应该可以帮助您解决问题。