Laravel从嵌套关系中检索特定字段

时间:2018-10-07 14:18:48

标签: laravel-5 eloquent

我有一些嵌套关系, 以下是我的模型: 帖子,主题和BookPage。 及其关系:

发布

class Post extends Model
{

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

}

主题

class Thread extends Model
{

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

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

}

BookPage

class BookPage extends Model
{

    public function threads(){
        return $this->hasMany(App\Threads);
    }

}

现在我想获取包含书页和主题的帖子,但是只有一些字段允许只说主题名和书名

我已经阅读了有关检索关系的信息,并且做得与文档中所述的完全一样,但这是我的问题:

当我检索没有指定字段的关系帖子时,我得到的结果很好:

查询:

$posts = Post::with('thread.bookpage:id,title)->get();
return $posts->toArray();

结果:

Result

但是当我同时为bookpage字段和线程字段指定字段时,我将bookpage设为null。 我仅能为书页或线程获得某一关系的特定字段。 我尝试通过以下方式进行查询:

$posts = Post::with('thread.bookpage:id, ...')->get();
//thread:all fields, bookpage:specified fields

$posts = Post::with('thread.bookpage', 'thread:id, ...')->get();
//thread:specified fields, bookpage:bull

如果我尝试为两个字段都指定字段,则结果如下: enter image description here

那么我如何仅从关系及其嵌套关系中获取特定字段?

1 个答案:

答案 0 :(得分:1)

您必须选择Laravel将急切的加载结果与其父母匹配所需的所有外键(在这里:thread.book_page_id

$posts = Post::with('thread:id,book_page_id', 'thread.bookpage:id,title')->get();