Search code examples
mysqllaraveleloquenteager-loadingeloquent-relationship

Laravel: where statement on with relationship


I want to do a query in laravel with multiple relationships and multiple where statements over the relationships but it doesn't go well.

Here's my code.

$orders = Order::with("customer")
            ->with("user")
            ->with("measuring_user")
            ->where("description", "like", "%" . $search . "%")
            ->orWhere("customers.name", "like", "%" . $search . "%")
            ->get();

I get the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customers.name' in 'where clause' (SQL: select * from `orders` where (`description` like %% or `customers`.`name` like %%) and `orders`.`deleted_at` is null)

The query should filter orders where one of both conditions is true.

When i do the customer where statement in the with function it doesn't work either:

    $orders = Order::with(["customer" => function($query) use ($search) {
        $query->where("name", "like", "%" . $search . "%");
    }])
    ->with("user")
    ->with("measuring_user")
    ->where("description", "like", "%" . $search . "%")
    ->get();

In this case it founds some orders without a customer. It does the where statement on the relationship instead of the whole order query.

Hope one of you can help me out.


Solution

  • Try this

    $orders = Order::with('customer', 'user', 'measuring_user')->whereHas('customer', 
      function($q) use ($search) {
        return $q->where('name', 'like', '%' . $search . '%');
      })->where('description', 'like', '%' . $search . '%')->get();
    

    Instead of using multiple with function, you can pass multiple relations to it using comma-separated values (like above).

    To query on the relation use whereHas function.