Laravel 拉威尔有很多身份证或其他身份证

Laravel 拉威尔有很多身份证或其他身份证,laravel,eloquent,has-many,Laravel,Eloquent,Has Many,如何在模型中使用函数来实现这一点 Select * from friends where (user_id = 22 or content_id = 22) and type=2 and situation = 1; 我试过了,但它会出错 public function friends() { return $this->hasMany('Friends',function ($query) { $query->where('content_id', $t

如何在模型中使用函数来实现这一点

Select * from friends where (user_id = 22 or content_id = 22) and type=2 and situation = 1;
我试过了,但它会出错

public function friends() { 
    return $this->hasMany('Friends',function ($query) {
        $query->where('content_id', $this->attributes['id']);
        $query->orWhere('user_id',$this->attributes['id']);
    })->where('type',2)->where('situation',1)->orderBy('id','DESC');
}

首先,你的模特名是“朋友”还是“朋友”?假设您遵循约定,并对模型名称使用单数时态,则应该可以:

return $this->hasMany('Friend')->where(function($query) {
    $query->where('content_id', $this->attributes['id']);
    $query->orWhere('user_id',$this->attributes['id']);
})->where('type',2)->where('situation',1)->orderBy('id','DESC');

换句话说,在hasMany()关系之后添加额外的查询参数,而不是作为第二个参数的闭包。

错误消息是什么?@lukasgeiter我用这种方式@foreach($users->friends as$friend){{{{$friend->id}@endforeach错误:类Closure的对象无法转换为string。您是否应该在单用户模型上调用
朋友
?我正在为一个用户调用朋友$users=User::where('username',$username)->where('type','1')->first();好的,我只是有点困惑,因为用户的复数形式。您的代码通常看起来不错。你能删除
{{$friend->id}
部分以确保我们在正确的位置搜索吗?