苗条 php / Eloquent hasMany-relation 的自定义查询
Slim php / Eloquent custom query for hasMany-relation
我目前正在使用 Slim php-框架和 eloquent-数据库:
https://www.slimframework.com/docs/cookbook/database-eloquent.html
我想做的是使用自定义 SQL-query 来设置两个模型的 hasMany-relation。
比方说,我有两个模型 "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;
,但仍然保持与用户条目关联的条目模型 属性。这可能吗?
如果我没有正确理解你的问题,你可以这样做:
$userentries = User::where('some', 'conditon')->with('entries')->get();
所以您基本上只需将 with('entries')
添加到您的查询中。
嗯,找到了一个干净的解决方案,它是 selectRaw() 和 eloquent 本地范围的组合:https://laravel.com/docs/5.4/eloquent#local-scopes
原型:
我尝试使用 query() 函数来找出可行的方法并想出了这个
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();
我目前正在使用 Slim php-框架和 eloquent-数据库: https://www.slimframework.com/docs/cookbook/database-eloquent.html
我想做的是使用自定义 SQL-query 来设置两个模型的 hasMany-relation。
比方说,我有两个模型 "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;
,但仍然保持与用户条目关联的条目模型 属性。这可能吗?
如果我没有正确理解你的问题,你可以这样做:
$userentries = User::where('some', 'conditon')->with('entries')->get();
所以您基本上只需将 with('entries')
添加到您的查询中。
嗯,找到了一个干净的解决方案,它是 selectRaw() 和 eloquent 本地范围的组合:https://laravel.com/docs/5.4/eloquent#local-scopes
原型:
我尝试使用 query() 函数来找出可行的方法并想出了这个
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();