简体   繁体   English

如何使用Laravel eloquent在多个表中存储数据

[英]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. 我想用eloquent将数据存储在三个表中。 My tables are as follow 我的表格如下

users, DrivingSession, Media ,DrivingSession model contains the user_id and Media model have the driving_session_id. users,DrivingSession,Media,DrivingSession模型包含user_id,Media模型包含driving_session_id。 I want to store DrivingSession image/videos created by specific user inside the Media model.My model functions are. 我想在Media模型中存储由特定用户创建的DrivingSession图像/视频。我的模型功能是。

Users.php Users.php

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

DrivingSession.php 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. 我想存储user_id,以便在DrivingSessions表和附加的Media to Medias表中进行参考。 how can I do this ? 我怎样才能做到这一点 ?

If there is only 1 user per driving session then it should be a BelongsTo relationship. 如果每个驾驶会话只有一个用户,那么它应该是BelongsTo关系。

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_id设置db表,那么您应该能够运行

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

And that will automagically populate the user_id column in the drivingsession. 这将自动填充drivesession中的user_id列。

You would do a similar thing on media and again I think it is more likely you want belongsTo rather than belongsToMany; 你会在媒体上做类似的事情,我认为你更有可能想要belongsTo而不是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');
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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