是否可以使用with方法使用预先加载但是给它另一个名字?就像是:
->with('documents as product', 'documents.documents as categories')
Run Code Online (Sandbox Code Playgroud)
我有一个文档表,可以是产品或类别,渴望加载工作,但不是那么友好,只通过文档名称而不是它真正的文件名来检索文档.
我已经浏览了laravel文档,我没有得到With或Load in queries 之间的不同,在哪种情况下我们需要使用With或Load?请描述一下
Model::find(1)->with('firstModel','SecondModel');
Model::find(1)->load('firstModel','SecondModel');
Run Code Online (Sandbox Code Playgroud) Laravel文档中Eager Loading部分的第一句是:
当访问Eloquent关系作为属性时,关系数据是"延迟加载".这意味着在您首次访问该属性之前,实际上不会加载关系数据.
在本节的最后一段中说明:
要仅在尚未加载关系时加载关系,请使用loadMissing方法:
public function format(Book $book)
{
$book->loadMissing('author');
return [
'name' => $book->name,
'author' => $book->author->name
];
}
Run Code Online (Sandbox Code Playgroud)
但我没有看到目的$book->loadMissing('author').这是在做什么吗?
如果我删除这一行会有什么区别?根据第一句话,无论如何,作者$book->author->name都是懒惰的,对吧?
我正在创建一个Reply模型,然后尝试返回具有所有者关系的对象。这是返回空对象的代码:
//file: Thread.php
//this returns an empty object !!??
public function addReply($reply)
{
$new_reply = $this->replies()->create($reply);
return $new_reply->with('owner');
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将with()方法换成load()方法以加载所有者关系,则可以得到预期的结果。那就是返回的回复对象及其相关的所有者关系:
//this works
{
$new_reply = $this->replies()->create($reply);
return $new_reply->load('owner');
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么。寻找澄清。
谢谢,耶
我的目标是创建一个具有评级关系的书店 API 端点。Book & Rating的关系是这样的:
书型
/**
* a book has many ratings
*/
public function ratings()
{
return $this->hasMany(Rating::class, 'book_id')->orderBy('created_at', 'ASC');
}
Run Code Online (Sandbox Code Playgroud)
评级模型
/**
* a rating belongs to a book
*/
public function book()
{
return $this->belongsTo(Book::class);
}
Run Code Online (Sandbox Code Playgroud)
我的 BookResource 看起来像这样
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\RatingResource;
class BookResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
// return parent::toArray($request);
return …Run Code Online (Sandbox Code Playgroud) php ×5
laravel ×4
laravel-5 ×2
eloquent ×1
laravel-5.2 ×1
laravel-5.4 ×1
laravel-5.7 ×1
mysql ×1