早上好/下午/晚上好!
我有 2 个模型,用户和帖子
用户.php
public function getRouteKeyName()
{
return 'user_name';
}
public function posts()
{
return $this->hasMany(Post::class, 'by_id', 'id');
}
我在用户表中有两条记录
|--------------------------------------------|
| id | user_name | ... | ... |
|--------------------------------------------|
| 1 | megamanx | ... | ... |
| 2 | black_zero | ... | ... | // Edited
Post.php
public function getRouteKeyName()
{
return 'slug';
}
public function by()
{
return $this->belongsTo(User::class, 'by_id', 'id');
}
我在帖子表中有一条记录
|----------------------------------------------------|
| id | by_id | slug | ... |
|----------------------------------------------------|
| 1 | 1 | test-first-post | ... |
在我的路线
Route::group(['prefix' => '{user}', function () {
Route::get('/', function (User $user) {
return View::make('user.index', compact('user'));
});
Route::get('/{post}', function (User $user, Post $post) {
return View::make('post.index', compact('user', 'post'));
});
});
如您所见,我为 Useruser_name
和 Post使用 Route 模型绑定slug
因此,当我访问路线时,例如:
127.0.0.1:8000/megamanx/test-first-post
// it return the correct owner
用户 megamanx 是帖子的所有者(test-first-post)
但是,当我尝试将用户参数传递给其他用户时,例如:
127.0.0.1:8000/black_zero/test-first-post
// Hey you don't own that post!
并且所有者帖子名称更改为 black_zero,但他不拥有该帖子
那么如何解决这个问题呢?我希望当用户尝试将 , 更改user_name
为其他内容时,返回 404。因为只有用户megamanx
自己的帖子test-first-post
我总是对批评持开放态度,因为我想成为一个更好的开发人员,如果上面的方法(路线,模型等)有任何错误,请纠正我!谢谢(·∀·)ノ</p>
英语不好见谅( ̄▽ ̄*)ゞ</p>
提前致谢!