[英]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.