我的项目中有以下数据库结构:
products table
images table
product_images table
with image_id, product_id, sort_order, main
其中“main”标志表示它是否是产品主图像。
有没有什么方法可以有一个雄辩的函数来获取产品的主要图像而不必调用 Product::with(['images.image'])
?
喜欢:
public function mainImage() {
return $this->belongsToThrough(Image::class, ProductImages::class ,...)->where('main', true);
}
我尝试了 hasOneThrough 函数,但它不起作用。 谢谢。
答案 0 :(得分:0)
public function image() {
return $this->belongsToOne(Image::class, ProductImages::class ,...)->where('main', true);
}
在产品模型中创建此函数
并称之为Product::with('image')
答案 1 :(得分:0)
最后我可以通过创建一个 BelongsToOne 关系来解决(因为我需要一个 Relation 实例来返回)。它可能对其他开发者也有用。
class BelongsToOne extends BelongsToMany {
public function getResults() {
$result = parent::getResults();
return $result ? $result->first() : null;
}
}
并使用
扩展核心模型类public function belongsToOne($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = null, $relation = null) {
if (is_null($relation)) {
$relation = $this->guessBelongsToManyRelation();
}
$instance = $this->newRelatedInstance($related);
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
if (is_null($table)) {
$table = $this->joiningTable($related, $instance);
}
return $this->newBelongsToOne(
$instance->newQuery(), $this, $table, $foreignPivotKey,
$relatedPivotKey, $parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(), $relation
)->limit(1);
}
protected function newBelongsToOne(\Illuminate\Database\Eloquent\Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey,
$parentKey, $relatedKey, $relationName = null) {
return new BelongsToOne($query, $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName);
}
我可能看起来很笨拙,但它也适用于急切加载。