[英]How should make this relationship and access data in Laravel
我有4张桌子:
表名:客户
栏位:编号,名称,子弹头
表名:项目
栏位:id,子弹
表名称:project_translation
字段:id,语言环境,project_id,标题
表名称:client_project
字段:id,client_id,project_id
关系
在项目模型中
public function clients()
{
return $this->belongsToMany(Client::class,'client_project')->withTimestamps();
//return $this->belongsToMany('Client')->withTimestamps()->orderBy('priority', 'desc');
}
在客户端模型中
public function projects()
{
return $this->belongsToMany(Project::class,'client_project')->withTimestamps();
}
public function translate()
{
return $this->belongsToMany(ProjectTranslation::class,'project_translations')->withTimestamps();
}
在Client_Project模型中
public function clients()
{
return $this->hasMany('App\Models\Project');
}
public function projects()
{
return $this->hasOne('App\Models\Client');
}
在ProjectTranslation模型中
public function client()
{
return $this->hasMany('App\Models\Client');
}
我试图像这样访问控制器中的数据 :
$client_project = Client::find($id)->translate;
return $client_project;
这给了我下一个错误:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique
table/alias: 'project_translations' (SQL: select
`project_translations`.*, `project_translations`.`client_id` as
`pivot_client_id`, `project_translations`.`project_translation_id` as
`pivot_project_translation_id`, `project_translations`.`created_at` as
`pivot_created_at`, `project_translations`.`updated_at` as
`pivot_updated_at` from `project_translations` inner join
`project_translations` on `project_translations`.`id` =
`project_translations`.`project_translation_id` where `project_translations`.`client_id` = 22)
我不确定,但是我认为人际关系出了点问题。
我在客户端刀片中,我想显示此客户端项目的项目翻译。
正如我在评论中所说,我不是Laravel用户,在这里我格式化了您的查询使其可读。 但是我知道Sql
select
`project_translations`.*,
`project_translations`.`client_id` as `pivot_client_id`,
`project_translations`.`project_translation_id` as `pivot_project_translation_id`,
`project_translations`.`created_at` as `pivot_created_at`,
`project_translations`.`updated_at` as `pivot_updated_at`
from
`project_translations` <-- Duplicate Table with no alias
inner join
`project_translations` on `project_translations`.`id` = `project_translations`.`project_translation_id`
where
`project_translations`.`client_id` = 22
您不需要Client_Project
模型。
在项目模型中
public function clients()
{
return $this->belongsToMany(Client::class,'client_project')->withTimestamps();
}
public function translates()
{
return $this->hasMany(ProjectTranslation::class);
}
在客户端模型中 :
public function projects()
{
return $this->belongsToMany(Project::class,'client_project')->withTimestamps();
}
在ProjectTranslation模型中 :
public function project()
{
return $this->belongsTo('App\Models\Project');
}
在控制器中:
$client_projects = Client::find($id)->projects; //all client projects
return $client_projects;
在获取此$client_projects
并对其进行循环之后,在视图中,您可以通过以下方式获取项目的翻译:
$client_project->translates // for single projects you will get its translates :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.