Php Laravel withPivot未返回pivot额外字段
我有两种型号的产品和商店 店内型号我有以下代码:Php Laravel withPivot未返回pivot额外字段,php,laravel,Php,Laravel,我有两种型号的产品和商店 店内型号我有以下代码: public function products() { return $this->belongsToMany(Product::class,'product_store')->withPivot('price','qty','is_block'); } public function scopeDistance($query, $latitude, $longitude, $distanc
public function products()
{
return $this->belongsToMany(Product::class,'product_store')->withPivot('price','qty','is_block');
}
public function scopeDistance($query, $latitude, $longitude, $distance, $columns = ['*'])
{
return $query->select($columns)
->selectRaw('( 6372.795477598 * acos( cos( radians(' . $latitude . ') ) *
cos( radians(latitude) ) *
cos( radians(longitude) - radians(' . $longitude . ') ) +
sin( radians(' . $latitude . ') ) *
sin( radians(latitude) ) ) )
AS distance')
->having('distance', '<=', $distance);
}
我有一个产品资源,代码如下:
public function store()
{
return $this->belongsToMany(Store::class, 'product_store', 'product_id', 'store_id')->withPivot('price', 'qty', 'is_block');
}
protected $with = ['brand', 'category', 'likes','store'];
public function toArray($request)
{
$user = auth('api')->user();
($store_id = \App\Models\Store::distance($user->addresses()->first()->latitude,$user->addresses()->first()->longitude,10)->first());
$store = \App\Models\Store::find($store_id);
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'slug' => $this->slug,
'price' => $this->price,
// 'real_price' => isset($store) ? $store->pivot->price : $this->pivot->price,
'category_id' => $this->category_id,
'viewed' => $this->viewed,
'is_active' => $this->is_active,
'qty_change' => $this->qty_change,
'limit' => $this->limit,
'images' => $this->images,
'brand_id' => $this->brand_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'store' => $store ,
'brand' => $this->brand,
'category' => $this->category,
'likes' => $this->likes,
'liked' => auth('api')->check() ? ((DB::table('wish_lists')->where('product_id', $this->id)->where('user_id', $user->id)->first()) ? 1 : 0) : 0
];
}
public function with($request)
{
return [
'meta' => [
'store' => $this->store[0] ?? null,
'category' => $this->category,
],
];
}
所以当我使用$store=\App\Models\store::find($store\u id)
它应该在我的存储关系中返回一个透视
,但它没有这样做。请帮我解决这个问题
提前感谢您如果您想在检索商店时加载pivot,您必须立即加载它 在
Store.php
模型中:
protected $with = ['products'];
这句话似乎是:
($store_id = \App\Models\Store::distance($user->addresses()->first()->latitude,$user->addresses()->first()->longitude,10)->first());
正在返回存储模型,应进行更改:
$store = \App\Models\Store::distance($user->addresses()->first()->latitude,$user->addresses()->first()->longitude,10)->first();
您已经在其中一个模型的数组中包装了使用Pivot的
的参数。顺便说一句,包装代码以防止出现长行有助于您更容易地发现此类错误。@miken32您能用一个答案解释您的意思吗?我不明白,再清楚不过了。在Store::products()
中,您已将参数包装到数组中的withPivot()
。@miken32 hmmm我更改了它,但结果没有更改