首页 > 解决方案 > 雄辩的选择所有具有多对多关系的表

问题描述

我有 3 个表(工作流、用户、工作流_用户),我想选择工作流_用户表的视图列。

class Workflow extends Model
{

    public function user()
    {
        return $this->belongsToMany(User::class,'workflow_user');
    }
}
class User extends Model
{

    public function works()
    {
        //return $this->belongsToMany(Role::class);
        return $this->belongsToMany(Workflow1::class,'workflow_user');
    }
}

工作流_用户表

class WorkflowUser extends Model
{

    protected $table = 'workflow_user';
    
    protected $fillable = [
        'workflow1_id','user_id','view'
    ];

    protected $primaryKey = 'id';
    
    public $timestamps = false;
}

要从 workflow_user 表中获取数据,我这样做

$workflow = User::find($idconnect)->works()->orderBy('created_at','desc')->paginate(10);

当我提出这个请求时,它没有给我 workflow_user(workflow1_id,user_id,view) 表的数据。

标签: phplaraveleloquent

解决方案


如果你有数据透视表的模型,你应该让它扩展Pivot类并在关系的定义中使用它。

此外,您需要在查询结果中手动包含不是外国 id 的字段。

class Workflow extends Model
{
    public function user()
    {
        return $this->belongsToMany(User::class, 'workflow_user', 'workflow_id', 'user_id')
                    ->using(WorkflowUser::class)
                    ->withPivot(['id', 'view']);
    }
}
class User extends Model
{
    public function works()
    {
        return $this->belongsToMany(Workflow::class, 'workflow_user', 'user_id', 'workflow_id')
                    ->using(WorkflowUser::class)
                    ->withPivot(['id', 'view']);
    }
}

工作流_用户表

class WorkflowUser extends Pivot
{
    protected $table = 'workflow_user';    
    protected $fillable = ['workflow_id', 'user_id', 'view'];
    protected $primaryKey = 'id';
    public $incrementing = true;
    public $timestamps = false;
}
$workflow = User::findOrFail($idconnect)
                ->works()
                ->orderBy('created_at', 'desc')
                ->paginate(10);

推荐阅读