Laravel Eloquent在父表

时间:2016-03-24 08:19:54

标签: laravel eloquent

我有这些表格:

  1. 地方:id,name,address
  2. 用户:id,name,email
  3. 评论:id,place_id, user_id, title,review,as_anoniem;
  4. 即使as_anoniem为1,user_id也会被填充。

    现在我希望获得所有地点的所有评论,除​​了as_anoniem = 1的用户以外的用户。

    这样的事情:

            Place::with(['review'=>function($qry){
    $qry->with('user')->where('as_anoniem',1);
    }])
    

    这不完全正确,因为它只返回as_anoniem = 1

    的评论

    我怎样才能实现这一目标呢?

3 个答案:

答案 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&的名称空间ReviewApp,它们位于同一目录中。

更新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);
}

答案 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);
    }
}
相关问题