是否可以使用 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
可以是一个产品,也可以是一个类别,这在逻辑上似乎没有多大意义。部分问题可能可以通过重新考虑数据库和关系的结构来解决。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)