根据关系Laravel 5.8和Eloquent更新数据库表

时间:2019-04-05 23:05:02

标签: php laravel eloquent

我在更新属于另一个表的表时遇到问题。 我有一个用户表和一个食谱表。配方模型属于用户模型,而用户模型具有许多配方。

每个食谱在我的索引视图中都显示为一张小卡片,在该卡片上以及每个单独的显示页面上,我正在打印食谱->作者。创建食谱时,它将从用户表中获取用户名属性,并将其设置为食谱表中的作者属性。但是,当我更新用户的用户名时,配方表中的author属性不会相应地更新。

用户模型

 public function recipes(){
        return $this->hasMany('App\Recipe');
    }

食谱模型

 public function user(){
        return $this->belongsTo('App\User');
    }

我可以在更新用户时在UserController中添加一些逻辑来解决这个问题吗?

UserController @ update

$user = Auth::user();

        $this->validate(request(), [
            'name' => 'required',
            'username' => 'required',
        ]);

          // Handle File Upload 
          if(request()->hasfile('profile_pic')){
            // Get filename with extension
            $fileameWithExt = request()->file('profile_pic')->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($fileameWithExt, PATHINFO_FILENAME);
            // Get just extension
            $extension = request()->file('profile_pic')->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            // Upload Image
            $path = request()->file('profile_pic')->storeAs('public/profile_pictures', $fileNameToStore);
        } else {
            $fileNameToStore = 'noimage.jpg';
        }

        $user->name = request('name');
        $user->username = request('username');
        $user->description = request('description');
        $user->location = request('location');
        if(request()->hasFile('profile_pic')){
            $user->profile_pic = $fileNameToStore;
        }
        $user->push();

        $user_id = Auth::user()->id;
        return redirect()->route('user', ['id' => $user_id]);
    }

我已经阅读了Laravel文档,找不到任何可以完全满足我所寻找的东西。希望得到任何指导!

2 个答案:

答案 0 :(得分:2)

您是说要将username存储在users中,并且想将确切的username存储在author的{​​{1}}中?

为什么不使用关系recipes引用名称。它将根据您的$recipe->user->username中的users查询您的user_id表,并为您获取recipes

这样就不会在数据库中存储重复数据。应该只有一个Single Source of Truth。您可以根据username获取用户数据,没有必要存储另一组数据并在源发生更改时不断更新。

如果您发现查询整个user_id模型比较繁琐,则可以使用User仅查询Recipe::with('users:id,username')->get()

如果要保持当前的username,可以:

$recipe->author

答案 1 :(得分:1)

如果您在迁移文件上设置了外键,则可以将<select id="countries"></select> <select id="cities"></select> <select id="districts"></select>子句添加到->onUpdate('CASCADE')表迁移上的外来用户名

注意:onCascade外键约束也可以在Laravel之外使用,因为它仅依赖于数据库引擎对外键的支持。

无论如何,请务必谨慎确认,因为您必须确保新选择的用户名尚未被其他人使用。

假设您的用户模型已连接到recipes表并具有一个users主键,请确保将用户名列设置为唯一 strong>在数据库中,并相应地“验证”用户输入。

前者是通过再次编辑迁移来完成的。

可以通过修改以下规则来解决后者:

id

注意:如果您修改迁移,则必须重新运行它们才能应用修改。