php - 雄辩的选择所有具有多对多关系的表
问题描述
我有 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) 表的数据。
解决方案
如果你有数据透视表的模型,你应该让它扩展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);
推荐阅读
- ios - 如何为工作区设置 Jenkins Xcode 插件?
- git - SVN 到 git 的转换:分支形成
- reactjs - 在 react-native 中获取我的应用程序版本的干净方法
- spring-boot - org.thymeleaf.exceptions.TemplateProcessingException:在此上下文中只允许返回数字或布尔值的变量表达式
- android - Bootstrap 方法返回 null - Android 在启动时立即崩溃
- flutter - 如何检查屏幕阅读器是否正在使用 Flutter
- docker - 在反向代理后面运行 Neo4J (web) 并连接到“bolt://localhost:7687”
- r - 使用geom_smooth时如何在ggplot中以x轴因子为条件更改线型?
- javascript - 带有 ASP.NET 网络表单的 SweetAlert 提示
- c# - 在分组的 ListView 中显示组标题