问题
I'm currently working with Slim php-framework and eloquent-database: https://www.slimframework.com/docs/cookbook/database-eloquent.html
What I want to do is to use a custom SQL-query to set up a hasMany-relation of two models.
Let's say, I have two models "User" and "Entry".
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
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;
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?
回答1:
If I'm understanding your question correctly, you can do this:
$userentries = User::where('some', 'conditon')->with('entries')->get();
So you basically just add with('entries')
to your query.
回答2:
Well, found a clean solution which is a combination of selectRaw() and eloquent local scopes: https://laravel.com/docs/5.4/eloquent#local-scopes
prototype:
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();
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();
来源:https://stackoverflow.com/questions/43130464/slim-php-eloquent-custom-query-for-hasmany-relation