简体   繁体   中英

How to store data in multiple tables using Laravel eloquent

I've Module that have multiple media. I want to use eloquent to store data in three table. My tables are as follow

users, DrivingSession, Media ,DrivingSession model contains the user_id and Media model have the driving_session_id. I want to store DrivingSession image/videos created by specific user inside the Media model.My model functions are.

Users.php

public function drivingsessions(){
    return $this->hasmany(DrivingSession::class);
}

DrivingSession.php

public function user(){
    return $this->belongsToMany(User::class);
}

public function Medias(){
     return $this->hasMany(Media::class);
}

Media.php

public function drivingSession(){
    return $this->belongsToMany(DrivingSession::class);
}

I want to store user_id for reference in DrivingSessions table and the attached Media to Medias table. how can I do this ?

If there is only 1 user per driving session then it should be a BelongsTo relationship.

public function user()
{
 return $this->belongsTo(User::class);
}

Providing that you have setup your db table with a user_id you should then be able to run

$user->drivingsessions()->save($driving_session);

And that will automagically populate the user_id column in the drivingsession.

You would do a similar thing on media and again I think it is more likely you want belongsTo rather than belongsToMany;

$driving_session->medias()->save($media);

If you are creating the resource then you can use the below

$driving_session = $user->drivingsessions()->create([
    'title' => $request->input('title'),
]);

Then you can use the captured resource to update the media

$driving_session->medias()->create([
    'media' => $request->input('media');
])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM