3 回答

TA貢獻1846條經(jīng)驗 獲得超7個贊
但我希望“圖像”只有 url 作為字符串,例如:
"images":[1.png,2.png,3.png .....]我該怎么辦?
最快的解決方案是將$visible
屬性添加到您的App\Images
模型中,如下所示:
public $visible = ['url'];
這將從 json 中刪除所有字段,包括pivot
字段,但visible
屬性中定義的字段除外。此解決方案工作正常,但它仍然選擇圖像表中的所有列,如果您希望它只為關(guān)系選擇最少的必填字段(以便提高性能),您可以執(zhí)行以下操作:
$stocks = Stocks::with('images:url', 'tags')->get(); // this is a shortcut for selecting only url
請注意,上述解決方案適用于多對多 (N:N) 關(guān)系。但是,對于 hasMany (1:N),您還必須選擇主鍵和所有相關(guān)的外鍵。
希望能幫助到你。
更新
它有效,但如何刪除密鑰 url: 并僅存儲值 1,2,3
->pluck() 是執(zhí)行此操作的集合函數(shù),但是,您不能在不丟棄其余字段的情況下輕松地從遠距離關(guān)系中提取字段,但是這個宏可以解決問題。
->pluckDistant()
在你AppServiceProvider的boot方法下,添加這個宏函數(shù):
public function boot()
{
/**
* Shortcut to pluck a field in a relationship.
*
* @param string $relationship The relationship name
* @param string|array $value
* @param string|null $key
*/
collect()->macro('pluckDistant', function($relationship, $value, $key = null) {
return $this->map(function($item) use($relationship, $value, $key) {
$relation = $item->getRelation($relationship);
if (get_class($relation) == \Illuminate\Support\Collection::class ||
get_class($relation) == \Illuminate\Database\Eloquent\Collection::class) {
$item->setRelation($relationship, $relation->pluck($value, $key));
}
return $item;
});
});
}
然后,你這樣做:
$stocks = Stocks::with('images:url', 'tags')->get()->pluckDistant('images', 'url');

TA貢獻1995條經(jīng)驗 獲得超2個贊
您需要像這樣進行查詢:
$stocks = Stock::with(['tags','images' => function ($query) {
$query->get()->pluck('url');
}])->get();

TA貢獻1805條經(jīng)驗 獲得超10個贊
您可以在急切加載與函數(shù)的關(guān)系時傳遞閉包with()。
在那個閉包中,您可以使用 select 函數(shù)來過濾列。
$stocks = Stock::with('tags')
->with(['images' => function ($query) {
$query->select(['id', 'url']);
}])
->get();
更新
如果您只想要沒有鍵的值,則不能使用此方法。您必須在從數(shù)據(jù)庫中獲取數(shù)據(jù)后執(zhí)行此操作。像這樣..
$stocks = Stock::with('images', 'tags')->get()->map(function ($stock) {
$stock->images = $stock->images->map->url->values();
$stock->unsetRelation('images');
return $stock;
});
- 3 回答
- 0 關(guān)注
- 150 瀏覽
添加回答
舉報