是否可以使用 with 方法使用预加载但给它另一个名字?像这样的东西:
->with('documents as product', 'documents.documents as categories')
我有一个可以是产品或类别的文档表,预先加载可以正常工作,但对于仅通过文档名称而不是实际内容检索文档来说不太友好。
最佳答案
目前任何 Laravel 版本都不支持此功能。你最好的选择是复制你的关系并根据你的需要命名它们。例如:
class Post extends Model
public function documents() {
return $this->hasMany(Document::class);
}
public function products() {
return $this->hasMany(Document::class)
->where('type', 'product'); // Scope the query, if necessary
}
public function categories() {
return $this->hasMany(Document::class)
->where('type', 'category'); // Would a Document really be of type 'category', though? Looks like a code smell.
}
}
$postsWithAllDocs = Post::with('documents')->get();
$postsWithProductsOnly = Post::with('products')->get(); // Only eager load Documents of type 'product'
在旁注中,您提到 Document
可以是产品或类别,这在逻辑上似乎没有多大意义。部分问题可能可以通过重新考虑数据库和关系的结构来解决。
关于php - 使用 with 但给它另一个名字的预加载模型 - Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37985900/