简体   繁体   English

Laravel Eloquent 在父表中有许多条件

[英]Laravel Eloquent hasMany condition in parent table

I have these tables:我有这些表:

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

The user_id is filled even if as_anoniem is 1 .即使as_anoniem1也会填充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

How can I achieve this using ?如何使用实现这一目标?

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.假设UserReview的命名空间都是App ,它们在同一目录中。

Update After the original question was changed by OP:更新 OP 更改原始问题后:

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

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