[英]Laravel Eloquent hasMany condition in parent table
I have these tables:我有这些表:
places
id
name
address
users
id
name
email
reviews
id
place_id
user_id
title
review
as_anoniem
The user_id
is filled even if as_anoniem
is 1
.即使
as_anoniem
为1
也会填充user_id
。
Now I want to have all the reviews
for all the places
with the user
except for the ones with as_anoniem = 1
.现在,我想与
user
一起获得所有places
所有reviews
,除了as_anoniem = 1
。
Something like this:像这样的东西:
Place::with(['review' => function ($query) {
return $query->with('user')->where('as_anoniem', 1);
}]);
This is not fully correct as it returns only reviews
with as_anoniem = 1
.这并不完全正确,因为它只返回带有
as_anoniem = 1
reviews
。
You may try this:你可以试试这个:
$users = \App::User::with('reviews' => function($query) {
$query->where('as_anoniem', '!=', 1);
})->get();
This will require you to create a one-to-many
relationship in App\\User
model, for example:这将需要您在
App\\User
模型中创建one-to-many
关系,例如:
// App\User.php
public function reviews()
{
// namespace: App\Review
return $this->hasMany(Review::class);
}
Assumed that, the namespace for both User
& Review
is App
, they are in the same directory.假设
User
和Review
的命名空间都是App
,它们在同一目录中。
$places = \App::Place::with('reviews' => function($query) {
$query->with('user')->where('reviews.as_anoniem', '!=', 1);
})
->get();
Place Model:放置模型:
public function reviews()
{
// namespace: App\Review
return $this->hasMany(Review::class);
}
Review Model:审查模型:
public function user()
{
// namespace: App\User
return $this->belongsTo(User::class);
}
It is possible to use values of model in conditions:可以在条件下使用模型的值:
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);
}
}
You can check out this link https://stackoverflow.com/a/18600698/16237933 .您可以查看此链接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.