我有这些表格:
id,name,address
id,name,email
。id,place_id, user_id, title,review,as_anoniem
; 即使as_anoniem为1,user_id
也会被填充。
现在我希望获得所有地点的所有评论,除了as_anoniem
= 1的用户以外的用户。
这样的事情:
Place::with(['review'=>function($qry){
$qry->with('user')->where('as_anoniem',1);
}])
这不完全正确,因为它只返回as_anoniem = 1
的评论我怎样才能实现这一目标呢?
答案 0 :(得分:2)
你可以试试这个:
$users = \App::User::with('reviews' => function($query) {
$query->where('as_anoniem', '!=', 1);
})->get();
这需要您在one-to-many
模型中创建App\User
关系,例如:
// 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);
}
答案 1 :(得分:0)
可以在以下条件下使用模型的值:
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);
}
}
答案 2 :(得分:-1)
您可以查看此链接 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);
}
}