如果关系尚未被删除,如何使用其关系返回记录

时间:2016-07-29 22:43:44

标签: php laravel laravel-5.2

我正在使用Laravel 5.2并且在我的模型设置之间存在一些关系。

我有Product模型和Customer模型(产品有客户)。 我使用以下内容获取客户列表,但我也使用软删除。如果客户被软删除(关系),我不想退回产品。

我如何在Laravel中实现这一目标?

$products = Product::with('customer')->get(); - 想说"其中customer.deleted_at为空"

2 个答案:

答案 0 :(得分:1)

您必须在查询中调用has

$products = Product::with('customer')->has('customer')->get();

答案 1 :(得分:1)

正如@Lock所说,使用

$products = Product::with('customer')->has('customer')->get();

提示:相反 - 即仅获取已删除客户的产品(这里没有多大意义,但您将来可能会发现这一点很方便),请在下面使用

$deleted=Product::with(['customer' => function ($q) {
    $q->withTrashed();
    }])->onlyTrashed()->get();