Slim php / Eloquent custom query for hasMany-relation

落爺英雄遲暮 提交于 2019-12-11 07:17:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!