I'm having two models Project
and StartYear
I'm having a project_technical_details
table which holds most of the project information. So I've following table structure in project_technical_details
:
project_id construction_start construction_area floors .....
When we were developing we were storing construction_start as year. ie it was hard coded for ex 2012
, 2013
, 2019
etc... Now we want to establish a relationship by which we can manipulate data, so we created a model StartYear
and we have following table structure:
id year created_at updated_at
so in this model I defined relationship as:
public function projects()
{
return $this->belongsToMany(
'App\Project', 'project_technical_details', 'construction_start', 'project_id');
}
But in this case I want to relate with year
column not with the id
. How can I achieve it. Thanks.
Your pivot table should look like this:
|------------------------|
| year | project_id | ...|
|------------------------|
Then, in your StartYear
model:
public function projects()
{
return $this->belongsToMany(
'App\Project', 'project_techinical_details', 'project_id', 'year'
)
->whereColumn('project_techinical_details.construction_start', 'start_year.year');
}
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.