0

I have user and job model. their is many to many relation between them. Name of Pivot table in job_user. I want to store records in pivot table with job Type and job Title from Job table and user Name from user table. how will i store that?Here is relation between job and user.

Job Model

public function Job_User()
{
    return $this->belongs To Many('App\Http\Models\User', 'jobs_users', 'user_id', 'job_id')->with-pivot('user Name','job Type','job Title');;

}

My user Model

public function Job_User()
{
    return $this->belongs To Many('App\HTTP\Models\Job', 'jobs_users', 'user_id', 'job_id')->with Pivot('user Name','job Type','job Title');

}
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
waleed
  • 51
  • 1
  • 2
  • 6
  • AFAIK you don't store anything other than the keys in the pivot table. Its purpose isn't to store anything else. – Wild Beard Jul 05 '16 at 18:10
  • But i have to store that. – waleed Jul 05 '16 at 18:11
  • is their any way??? – waleed Jul 05 '16 at 18:11
  • You don't store that data in the pivot table. The user name goes in the user table, and the job title and type go in the job table. By binding job to user, or user to job, it creates a record in the pivot table. Once bound you can access your jobs ( if from user ) by doing `$user = User::find(1)->jobs` – Wild Beard Jul 05 '16 at 18:14
  • when i am saving id of job and user as foreign key in pivot table i also want to store the jobtype and tile from job and user name from user. i have created the extra columns in pivot table. – waleed Jul 05 '16 at 18:17
  • $trai = $req->$trainer_id; $job = $req->job_id; $j = Job::find($job); foreach ($req->student as $key) { $stud = User::find($key); $stud->Job_User()->attach($job, ['trainer_id' => $trai,'userName'=>$stud->userName,'jobType'=>$job->jobType]); } – waleed Jul 05 '16 at 18:21
  • this is my controller function – waleed Jul 05 '16 at 18:21
  • [See second answer](http://stackoverflow.com/questions/26566675/getting-the-value-of-an-extra-pivot-table-column-laravel) this may help. – Wild Beard Jul 05 '16 at 18:30
  • Looks like you have it. The second parameter is an array of updates to send to the pivot table. Is it not working for you? – user1669496 Jul 05 '16 at 20:17
  • While you can absolutely store data in extra columns in the pivot table (see withPivot() which is designed to access this data), they are correct to say that you shouldn't be storing any user data or job data in the users_jobs table, as the pivot table should only store info relevant to the actual pivot (such as when the pivot was made, etc.) – Leng Jul 05 '16 at 22:31
  • no,its not working while i am storing the job records in pivot table – waleed Jul 06 '16 at 07:26

0 Answers0