Laravel / Eloquant:我可以在模型中使用 "with" 函数时强制关系吗

Laravel / Eloquant: can i make relation mandatory while using "with" function in models

我有问题。我使用函数 with() 来关联 Eloquent 中的模型。有时并不是所有的数据都存在于某些关系模型中,所以它returns错误,有什么解决办法吗?

例如:

Author::whereId($authorId)->with('AuthorContactData')->with('AuthorSocialLinks');

有时 AuthorContactData 一位作者不存在。有什么解决方案可以忽略任何作者。怎么没有AuthorContactData

谢谢,

您可以使用 has():

添加这种约束
Author::whereId($authorId)
      ->has('AuthorContactData')
      ->with('AuthorContactData', 'AuthorSocialLinks')
      ->get();