Laravel 5 eloquent:选择特定的关系列

use*_*002 0 eloquent laravel-5

我有 2 个模型:作者和帖子

在我的 Post 模型中,我有一个作者函数(一对多(逆)):

public function author()
    {
        return $this->belongsTo('App\Author', 'author_id');
    }
Run Code Online (Sandbox Code Playgroud)

现在我想将以下信息导出到 Excel:

身份证 | 标题 | 作者姓名

这是我尝试过的:

$posts = Post::with(array(
        'author' => function ($query) {
            $query->select('name');
        }))->select('id', 'title')->get();
Run Code Online (Sandbox Code Playgroud)

我得到的是一个空的作者姓名列。

我怎么了?

mul*_*l14 6

从 Laravel 5.5 开始,您可以使用急切加载,只需使用字符串即可检索多个特定列

Post::with('author:id,name')->get()

Author::with('posts:id,author_id,title')->get()
Run Code Online (Sandbox Code Playgroud)

请注意,必须包含id或 外键 ( author_id),否则数据将为 null


Ale*_*huk 5

请尝试:

$posts = Post::with(['author' => function($query){
    $query->select(['id','name']);
}])->get(['id','title', 'author_foreign_key_in_posts_table']);
Run Code Online (Sandbox Code Playgroud)

有了它,您将能够获得:

$posts->first()->author->name;
$posts->first()->id;
$posts->first()->title;
Run Code Online (Sandbox Code Playgroud)

您可以使用迭代或其他方式代替 first() 进行导出。