[英]Slim php / Eloquent custom query for hasMany-relation
我目前正在使用Slim php-framework和eloquent-database: https : //www.slimframework.com/docs/cookbook/database-eloquent.html
我想要做的是使用自定义SQL查询来设置两个模型的hasMany关系。
比方说,我有两个型号“User”和“Entry”。
我的User.php看起来像这样
class User extends \Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function entries() {
return $this->hasMany('foo\bar\Entry');
}
}
要获取条目,我使用以下代码按预期工作。
$userentries = User::find(1)->entries
但是,我希望使用自定义SQL查询来获取条目
SELECT e.user_id, e.colB, SUM(e.colC - e.colD) as foobar from entries as e where e.user_id = 1 group by e.colB order by foobar DESC;
而不是SELECT * from entries where user_id = 1;
的默认SELECT * from entries where user_id = 1;
但仍保持Entry模型与User的entries属性相关联。 那可能吗?
如果我正确理解你的问题,你可以这样做:
$userentries = User::where('some', 'conditon')->with('entries')->get();
因此,您基本上只需在查询中添加with('entries')
即可。
好吧,找到了一个干净的解决方案,它是selectRaw()和雄辩的本地范围的组合: https ://laravel.com/docs/5.4/eloquent#local-scopes
我玩了查询() - 函数来找出,有什么可能,并提出了这个
Entry::query()->selectRaw("SUM(colC - colD) as foobar, colB")->where('user_id', 1)->groupBy('colB')->orderBy('foobar', 'DESC')->get();
Entry.php
模型如下所示:
class Entry extends \Illuminate\Database\Eloquent\Model {
public function scopeCustom($query) {
return $query->selectRaw("SUM(colC - colD) as foobar, colB")->groupBy('colB')->orderBy('foobar', 'DESC')->get();
}
}
我可以用它来调用它:
User::find(1)->entries()->custom();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.