在模型中,从belongsTo()关系中获得特定属性,而不附加整个集合

问题描述 投票:0回答:1

假设我想在图书模型中获取作者的名字

// app/Book.php
protected $appends = ['author_name'];

public function author() {
  return belongsTo(Author::class, 'author_id');
}

public function getAuthorNameAttribute() {
  return $this->author->name;
}

但是这也会将整个作者集添加到最终的书籍集中,这会在尝试加载100本书时增加加载时间,现在我通过这样的名字删除作者来解决这个问题] >

// app/Book.php
protected $appends = ['author_name'];

public function author() {
  return belongsTo(Author::class, 'author_id');
}

public function getAuthorNameAttribute() {
  $authorName = $this->author->name;
  unset($this->author);

  return $authorName;
}

有更好的方法吗?还是我错过了雄辩的功能?

欢呼声

假设我想在书籍模型中获取作者的名字// // app / Book.php protected $ appends = ['author_name'];公共函数author(){返回归属于(Author :: class,'author_id'); } ...

laravel
1个回答
0
投票

尝试在您的应用程序/Book.php中添加以下代码

© www.soinside.com 2019 - 2024. All rights reserved.