当然我可以使用order_by和第一个表中的列,但不能使用第二个表上的列,因为结果是部分的。
如果我使用'加入',一切都很完美,但我需要雄辩地实现这一目标。我做错了吗?
这是一个例子:
//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>';
}
}
答案 0 :(得分:1)
在您的模型中,您需要明确告诉关系按该字段排序。
所以在你的odt模型中添加:
public function hdt() {
return $this->has_many('hdt')->order_by('servicio', 'ASC');
}
这将允许在使用此关系时对第二个表进行排序,并且您不需要Fluent join语句中的order_by行。
答案 1 :(得分:0)
我建议不要将关系方法中的顺序列为编码主义者所建议的。你所建立的方法在功能上与编纂者的建议相同。
两种解决方案之间的区别在于,首先,您要通过hdt.servicio订购odt(所有结果)。在第二个中,您将按照自然顺序检索odt,然后按服务顺序排序每个odt包含的hdt。
第二个解决方案的效率也低得多,因为你要进行一次查询以获取所有的odt,然后对每个odt进行额外的查询来提取它的hdts。检查分析器。考虑到您的初始查询以及您只检索一列,这样的工作会起作用吗?
HDT::where( 'odt_id', '>', 0 )->order_by( 'servico' )->get('servico');
答案 2 :(得分:0)
现在我觉得这很简单!我必须在第二个表上进行查询,并使用函数odt()获取第一个表的内容,建立关系“belongs_to”
//solution
$data = Hdt::order_by('servicio')->get();
foreach($data as $hdt){
echo $hdt->odt->odt.' - '.$hdt->servicio.'<br>';
}
答案 3 :(得分:0)
简单的答案是:
$data = Odt::join('hdt', 'odt.id', '=', 'hdt.odt_id')
->order_by('hdt.servicio')
->get(array('odt.odt as odt','hdt.servicio as servicio'));
您可以使用Fluent做任何事情,您也可以使用Eloquent。如果您的目标是使用hdts
tho检索odts
,我建议使用反向查询以提高可读性:
$data = Hdt::join('odt', 'odt.id', '=', 'hdt.odt_id')
->order_by('hdt.servicio')
->get(array('hdt.servicio as servicio', 'odt.odt as odt'));
这两者都完全一样。
解释其原因:
每当您调用Posts::where(...)
之类的静态方法时,Eloquent将为您返回Fluent查询,与DB::table('posts')->where(...)
完全相同。这使您可以灵活地构建您喜欢的任何查询。这是一个例子:
// Retrieves last 10 posts by Johnny within Laravel category
$posts = Posts::join('authors', 'authors.id', '=', 'posts.author_id')
->join('categories', 'categories.id', '=', 'posts.category_id')
->where('authors.username', '=', 'johnny')
->where('categories.name', '=', 'laravel')
->order_by('posts.created_at', 'DESC')
->take(10)
->get('posts.*');