我一直在努力把所有作者从藏书中找出来。
$books = Books::all();
foreach($books as $book){ $book->author ...
这段代码将工作,但我想获得所有作者不使用循环
$allAuthorsThruBooks = Books::someQueryMaybe();
$allAuthorsThruBooks将显示作者列表。
谢谢!
假设所有模型都在Models目录AppModels
书模型
use AppModelsAuthor;
...
Class Books extends Model
{
public function author()
{
return $this->belongsTo(Author::class, 'author_id');
}
}
查询
$books = Books::with(['author'])->get();
// with condition
$books = Books::with(['author' => function($query)
$query->where(...);
])->get();
例子结果
[
id: 1,
name: 'Book One',
author: [
id: 1,
name: 'Maddog'
]
],
[...]
方法01
<尝试strong>摘下尝试strong>
$authorList = collect($books)->pluck('author')->unique();
// use ->toArray() if you want to convert into array
方法02
创建助手
namespace AppHelpers;
use IlluminateSupportArr;
class ArrHelper
{
public static function onlyValues($array = [], $keys = [])
{
return array_filter(
array_values(
Arr::only($array, $keys)
)
);
}
}
在控制器$authorList = collect(ArrHelper::onlyValues($books, ['author']));