Laravel避免在创建对象后在laravel上查询关系
问题描述:
如何避免在创建对象后查询关系?Laravel避免在创建对象后在laravel上查询关系
$store = new Store();
$store->name = 'Store 1';
$store->save();
return response()->json($store->products());
Laravel正在查询产品表。我想避免这种情况,因为我知道没有。这只是一个例子。
return response()->json([]);
是不是一种选择。在现实世界中,我真的需要使用$store->products()
。
答
使用模型的wasRecentlyCreated
属性标识,如果当前的请求生命周期中插入模型。
$data = $store->wasRecentlyCreated ? [] : $store->products();