Gon*_*afa 4 relationship laravel eloquent
我在两个表之间建立了关系,其中一个连接表只有一个结果。
当我定义 Laravel 的belongsToMany 关系时,与其返回一个只有一个元素的集合,不如让它单独返回该项目。
有没有办法在 Laravel 中对此进行建模?
提前致谢。
[编辑]
我将尝试使用经典的用户/角色示例来解释我想要什么。除了 deusers和roles表,我们还有一个users_roles数据透视表,它将存储用户拥有的所有角色。在任何给定时间,用户只能拥有一个活动角色(由active属性标识true)。
class User {
function role() {
return $this->belongsToMany('App\Role')->wherePivot('active', 'true');
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个关系定义,当我访问时,$user->role我会得到一个角色集合(只有一个元素)。我想要的是直接拥有该 Role 实例。
Mac*_*rek 14
就我而言,这是最直接的解决方案:
class User extends Model {
public function services()
{
return $this->belongsToMany(Service::class, 'service_user')
->using(ServiceUser::class)
->withPivot('user_id', 'service_id', 'is_main_service');
}
public function mainService()
{
return $this->hasOneThrough(Service::class, ServiceUser::class, 'user_id', 'id', 'id', 'service_id')
->where('is_main_service', 1);
}
}
Run Code Online (Sandbox Code Playgroud)
数据透视表类:
use Illuminate\Database\Eloquent\Relations\Pivot;
class ServiceUser extends Pivot
{
}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果你只需要一个关系,我不知道为什么你有belongsToMany,但是下面的代码可以帮助你:
public function products()
{
return $this->belongsToMany('App\Product');
}
public function specific_product()
{
return $this->products()
->where('column','value')->first();
}
Run Code Online (Sandbox Code Playgroud)
或者
public function getSpecificProductAttribute()
{
return $this->products()
->where('column','value')->first();
}
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题,并找到了一种非常干净的方法来解决它。
首先,更改返回结果的访问器函数的名称belongsToMany,以反映它们返回多个结果的事实。在你的情况下,这意味着使用roles而不是role:
function roles() {
return $this->belongsToMany('App\Role')->wherePivot('active', 'true');
}
Run Code Online (Sandbox Code Playgroud)
然后将以下内容添加到您的模型中:
protected $appends = ['role'];
public function getRoleAttribute() {
return $this->roles()->first();
}
Run Code Online (Sandbox Code Playgroud)
现在,当您致电时,$user->role您将获得第一个项目。
| 归档时间: |
|
| 查看次数: |
5566 次 |
| 最近记录: |