首页 > 解决方案 > Eloquent 注入多个模型关系

问题描述

所以我在 JeffreyWay 的截屏视频中了解到,我可以使用 Eloquent 从注入到另一个模型的模型中获取关联的 id。

我正在关注他关于 Laravel 5.4 的系列。

在这里,我有一个用户与帖子的一对多关系。

应用程序/帖子

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

在我的用户模型中,我有一个发布方法,其中注入了 Post 模型。publish 方法用于在数据库中创建一个帖子条目。

应用程序/用户

public function posts()
{
    return $this->hasMany(Post::class);
}

public function publish(Post $post)
{
    $this->posts()->save($post);
}

然后我在我的 PostsController 中有一个 store 方法,它在我的用户模型中调用 publish 方法。

帖子控制器

class PostsController extends Controller
{
     public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }

    public function store()
    {
        auth()->user()->publish(
           new Post(request(['title', 'body']))
        );
    }
}

当调用 publish 方法时,注入的 Post 类会自动将 user_id 设置为 save 方法。

我的问题是,在每个帖子都有评论的情况下,我如何建立这样的关系。这些评论与帖子和创建评论的用户相关联。

简而言之,当我调用 addComment 方法时,我应该同时拥有 user_id 和 post_id。

标签: laraveleloquentlaravel-5.6

解决方案


在您的问题中,您写道:

简而言之,当我调用 addComment 方法时,我应该同时拥有 user_id 和 post_id。

这是绝对正确的,没有问题。您不必通过类似方法设置这些属性$user->posts()->save($post)- 这只是为您完成工作的便捷方法(请参阅框架代码中的save($model)相关内容setForeignAttributesForCreate($model);这些方法只是为您设置外键属性)。

实际上,以下三种创建新帖子的方法是可以互换的:

// what you did
$user->posts->save(
    new Post([
        'title' => 'Hello', 
        'body' => 'World!',
    ])
);

// equivalent
Post::create([
    'user_id' => \Auth::user()->id, // or \Auth::id()
    'title' => 'Hello',
    'body' => 'World!',
]);

// also equivalent
$post = new Post([
    'user_id' => \Auth::user()->id, // or \Auth::id()
    'title' => 'Hello',
    'body' => 'World!',
]);
$post->save();

存储新评论时,您很可能会有这样的控制器,因为评论始终属于帖子,因此您需要帖子的引用:

class CommentsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }

    public function store(Post $post)
    {
        $comment = new Comment(request(['body']));
        $comment->user_id = \Auth::user()->id;
        $comment->post_id = $post->id;
        $comment->save();
    }
}

你也可以缩写它并写:

Comment::create(
    array_merge(request(['body']), ['user_id' => \Auth::id(), 'post_id' => $post->id])
);

推荐阅读