当使用雄辩的一对多时,如何在第二个表上“order_by” [英] How to 'order_by' on second table when using eloquent one-to-many
本文介绍了当使用雄辩的一对多时,如何在第二个表上“order_by”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当然,我可以在第一个表中使用order_by列,但不能使用第二个表中的列,因为结果是部分的。
Of course I can use order_by with columns in my first table but not with columns on second table because results are partial.
如果我使用'join'完美但我需要在雄辩中实现这一点。我做错了吗?
If I use 'join' everything works perfect but I need to achieve this in eloquent. Am I doing something wrong?
这是一个例子:
//with join
$data = DB::table('odt')
->join('hdt', 'odt.id', '=', 'hdt.odt_id')
->order_by('hdt.servicio')
->get(array('odt.odt as odt','hdt.servicio as servicio'));
foreach($data as $v){
echo $v->odt.' - '.$v->servicio.'<br>';
}
echo '<br><br>';
//with eloquent
$data = Odt::get();
foreach($data as $odt){
foreach($odt->hdt()->order_by('servicio')->get() as $hdt){
echo $odt->odt.' - '.$hdt->servicio.'<br>';
}
}
推荐答案
我看到这很简单!我必须在第二个表上做查询,并使用函数odt()建立关系belongs_to来获取第一个表的内容。
Now I see it was something simple! I have to do the query on the second table and get contents of the first table using the function odt() witch establish the relation "belongs_to"
//solution
$data = Hdt::order_by('servicio')->get();
foreach($data as $hdt){
echo $hdt->odt->odt.' - '.$hdt->servicio.'<br>';
}
这篇关于当使用雄辩的一对多时,如何在第二个表上“order_by”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文