繁体   English   中英

Laravel Eloquent 在父表中有许多条件

[英]Laravel Eloquent hasMany condition in parent table

我有这些表:

  1. places
    • id
    • name
    • address
  2. users
    • id
    • name
    • email
  3. reviews
    • id
    • place_id
    • user_id
    • title
    • review
    • as_anoniem

即使as_anoniem1也会填充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

如何使用实现这一目标?

你可以试试这个:

$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);
}

假设UserReview的命名空间都是App ,它们在同一目录中。

更新 OP 更改原始问题后:

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM