[英]Laravel Eloquent hasMany condition in parent table
我有這些表:
places
id
name
address
users
id
name
email
reviews
id
place_id
user_id
title
review
as_anoniem
即使as_anoniem
為1
也會填充user_id
。
現在,我想與user
一起獲得所有places
所有reviews
,除了as_anoniem = 1
。
像這樣的東西:
Place::with(['review' => function ($query) {
return $query->with('user')->where('as_anoniem', 1);
}]);
這並不完全正確,因為它只返回帶有as_anoniem = 1
reviews
。
如何使用eloquent實現這一目標?
你可以試試這個:
$users = \App::User::with('reviews' => function($query) {
$query->where('as_anoniem', '!=', 1);
})->get();
這將需要您在App\\User
模型中創建one-to-many
關系,例如:
// App\User.php
public function reviews()
{
// namespace: App\Review
return $this->hasMany(Review::class);
}
假設User
和Review
的命名空間都是App
,它們在同一目錄中。
$places = \App::Place::with('reviews' => function($query) {
$query->with('user')->where('reviews.as_anoniem', '!=', 1);
})
->get();
放置模型:
public function reviews()
{
// namespace: App\Review
return $this->hasMany(Review::class);
}
審查模型:
public function user()
{
// namespace: App\User
return $this->belongsTo(User::class);
}
可以在條件下使用模型的值:
class Content extends Model
{
// ...
/**
* Get linked content
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function linked()
{
return $this->hasMany(self::class, 'source_content_id', 'source_content_id')
->where('source_content_type_id', '=', $this->source_content_type_id)
->where('id', '<>', $this->id);
}
}
您可以查看此鏈接https://stackoverflow.com/a/18600698/16237933 。
class Game extends Eloquent {
// many more stuff here
// relation without any constraints ...works fine
public function videos() {
return $this->hasMany('Video');
}
// results in a "problem", se examples below
public function available_videos() {
return $this->videos()->where('available','=', 1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.