3 回答

TA貢獻2003條經驗 獲得超2個贊
檢查關系鍵是否已設置,即
!empty($post->user_id)
這樣可以避免不必要的數據庫查詢。顯然,這只適用于 belongsToRelationships。
對于其他關系類型,可以使用類的 has 方法,即
Post::has('user')
如果你已經有了模型,你可以做$post->newQuery()->has('user');
or $post->user()->exists()
。
所以,是的,有很多不同的選擇。

TA貢獻1809條經驗 獲得超8個贊
不確定您是否在尋找什么,但您可以使用 exists 輔助方法,如果關系存在,該方法將返回一個布爾值,
User::first()->has('dogs')->exists();
如果第一個用戶與狗有關系,將返回 true。

TA貢獻1816條經驗 獲得超4個贊
我發現解決方案基本上是一個遞歸函數
protected $relationNames = [];
function recursive($model){
foreach($model as $key => $value){
$this->relationNames[$key] =$value;
if(count($value->getrelations()) > 0){
$this->recursive($value->getrelations());
}
}
}
- 3 回答
- 0 關注
- 101 瀏覽
添加回答
舉報