针对hasMany关系的Slim php / Eloquent自定义查询 [英] Slim php / Eloquent custom query for hasMany-relation
问题描述
我正在使用Slim php-framework和eloquent-database:
https://www.slimframework.com/docs/cookbook/database-eloquent.html
I'm currently working with Slim php-framework and eloquent-database: https://www.slimframework.com/docs/cookbook/database-eloquent.html
我想做的是使用一个自定义SQL查询来设置两个模型的hasMany关系。
What I want to do is to use a custom SQL-query to set up a hasMany-relation of two models.
我有两个模型User和Entry。
Let's say, I have two models "User" and "Entry".
我的User.php看起来像这样
My User.php looks like this
class User extends \Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function entries() {
return $this->hasMany('foo\bar\Entry');
}
}
要获取条目,我使用以下代码,其工作原理如下:
To fetch the entries I use the following code which works as expected.
$userentries = User::find(1)->entries
但是,我希望使用自定义SQL查询来获取条目,如
But, I'd like the entries to be fetched with a custom SQL-query like
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 entry where user_id = 1; code>但仍保留与用户的条目属性相关联的条目模型。
instead of the default SELECT * from entries where user_id = 1;
but still keep the Entry-model associated to the User's entries property. Is that possible?
推荐答案
嗯,找到一个干净的解决方案,它是selectRaw()和雄辩的本地范围的组合: https://laravel.com/docs/5.4/eloquent#local-scopes
Well, found a clean solution which is a combination of selectRaw() and eloquent local scopes: https://laravel.com/docs/5.4/eloquent#local-scopes
我使用query() - 查找功能,可能发生了什么使用这个
I played around with the query()-functions to find out, what's possible and came up with this one
Entry::query()->selectRaw("SUM(colC - colD) as foobar, colB")->where('user_id', 1)->groupBy('colB')->orderBy('foobar', 'DESC')->get();
使用这个关系:
Entry.php
模型看起来像这样:
to use this in a relation:
the Entry.php
model looks like this:
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();
}
}
最后...
我可以通过以下方式调用它:
and finally...
I can call it with:
User::find(1)->entries()->custom();
这篇关于针对hasMany关系的Slim php / Eloquent自定义查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!