一段时间以来,我一直在努力弄清楚如何用Laravel雄辩的口才来完成这个查询。
查询:
DB::select('SELECT
n.id,
n.parent_id,
n.name,
n.file,
n.created_at AS ts,
f.mime,
f.extension,
IF(ch.id, 1, 0) AS dirs
FROM nodes AS n
LEFT JOIN nodes AS ch ON ch.parent_id=n.id
LEFT JOIN files AS f
ON n.file = f.id
WHERE n.parent_id=?
GROUP BY n.id',array($path));我有我的模型Node,它使用表nodes,我为我的Node模型有一个方法nodefile(),包括return $this->belongsTo('NodeFile');,这是我需要加入的另一个模块。NodeFile模块使用表files,这两个模块绑定在nodes.file和files.id上。
到目前为止,我得到的是:
Node::with(
array('nodefile'=>function($query){
$query->select('mime','extension');
})
)->where('name','LIKE','%'.$q.'%')->get(array(
'id', 'parent_id', 'name', 'file', 'created_at AS nts'
));但我仍然需要查询中的IF(ch.id,1,0) AS dirs。也没有做好自己的加入。
有谁知道如何以最好的方式做这件事吗?
发布于 2014-04-09 11:15:58
用下面的代码修复了它。
Node::
leftjoin('files','files.id','=','nodes.file')
->leftjoin('nodes AS ch','ch.parent_id','=','nodes.id')
->where('nodes.id','=',$path)
->groupBy('id')
->get(array(
'nodes.id',
'nodes.parent_id',
'nodes.name',
'nodes.file',
'nodes.created_at AS nts',
'files.mime',
'files.extension',
'ch.id AS dirs'
));感谢@MarkBarker让它变得原始的想法,这帮助我找到了这个解决方案。
https://stackoverflow.com/questions/22940253
复制相似问题