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