【发布时间】:2020-04-01 04:00:16
【问题描述】:
我是 Laravel API 的新手,我想返回一本推荐的书 === 1
在我的资源中,我有这个
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'about' => $this->about,
'content' => $this->content,
// 'image' => asset('/storage/'.$this->image),
'image' => $this->image_url,
// 'recommended' => $this->recommended,
'recommended' => $this->when($this->recommended === 1, $this->recommended),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'author' => $this->author,
];
我想在推荐时还书=== 1
我的桌子是这样的
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('about');
$table->string('image');
$table->string('image_url');
$table->string('epub_url');
$table->integer('author_id');
$table->string('publisher');
$table->year('year');
$table->boolean('recommended')->default(0);
$table->timestamps();
});
我可以使用这个在网络上实现同样的目标
public function index()
{
$data = array();
$data['recommends'] = Book::where('recommended', 1)->take(10)->get();
$data['latests'] = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('welcome', compact("data"));
}
但我不知道如何使用 Laravel API 复制相同的内容。
更新
我能够使用这个在网络上实现同样的事情public function index()
{
$data = array();
$data['recommends'] = Book::where('recommended', 1)->take(10)->get();
$data['latests'] = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('welcome', compact("data"));
}
但我不知道如何使用 Laravel API 复制相同的内容。
通常我会使用 API 资源获得所有类似的书籍或帖子
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'about' => $this->about,
'content' => $this->content,
'image' => $this->image_url,
'recommended' => $this->recommended,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'author' => $this->author,
];
并在我的控制器中这样调用它
public function indexapi()
{
return BookResource::collection(Book::with('author')->Paginate(16));
}
但是有些情况recommended==1,有些recommended==0,在这种情况下,我只想在推荐时返回数据==1
我知道我的问题很混乱
谢谢。
谢谢。
【问题讨论】:
-
归还什么书?这个资源首先是做什么用的
-
示例:我想返回一个帖子推荐的帖子。默认情况下,我将推荐设置为 0,这使它不被推荐,但是当推荐时它必须 == 1。这就是我在这里想要实现的。谢谢。
-
when方法用于有条件地添加一个属性,而不是您是否返回整个资源,感觉应该在您返回资源之前完成...添加到您的问题如何您正在使用此 API 资源 -
你能不能用代码的形式解释一下,这样我会更好理解,它可以让我自己解决类似的问题。谢谢。
-
感谢提示,我已经解决了。