在Laravel 4中发送模型嵌套数组的最佳方法是什么?

时间:2016-03-24 23:37:07

标签: laravel view eloquent models

我正在创建一个包含帖子列表的简单博客。每个帖子都有多个媒体(图片,视频等)。所以我有三个模型:Post(id,title,article,album_id等),Album(id,title,description等)和Media(id,url,type等)。帖子可能有专辑,专辑可以有多个媒体。

要生成包含我编码的帖子列表的页面,如下所示(BlogController):

public function generateList(){
        $posts = Post::where('subcategory_id','=','3')->orderBy('created_at', 'DESC')->paginate(30);

        return View::make('main.informativos')
            ->with('posts', $posts);
    }

如您所见,今天只有帖子被发送到视图。我的问题是:发送每个帖子的所有媒体的最佳方式是什么?记住有很多帖子。

1 个答案:

答案 0 :(得分:3)

在型号中预先指定外键 使用关键函数与外键[',' primarykey'
在条件
之前使用控制器中的功能 公司,国家职能是基于关系的 你再次怀疑..检查laravel doc

public function index()
{
    $Location = Location::with('Company', 'Country')
        ->where('company_id', '=', $company_id)
        ->get();
    return response()->json($Location, 200);
}