How to get the allocated data from the second table in Laravel?

I have two tables: usersand students. These tables are linked by fields:

users.id = studetns.user_id

I am trying to get information using the query:

$students = User::where(function ($query) use ($request) {

            // Filter by name
            if (($term = $request->get("name"))) {
                $query->where('name', 'like', '%' . $term . '%');
                $query->where('secondname', 'like', '%' . $term . '%');
            }

        })->with("details")->where('type', '2')->orderBy('name', 'desc')->get();
        dd($students);

You can see with("details")which should connect to the tables.

My model User:

public function details()
    {
        return $this->hasOne('App\Student', 'user_id', 'id');
    }

When I execute the request, I get an error:

select * from `users` where `type` = 2 order by `name` desc)

This means that there was no join to the second table where there are namefiels.

+4
source share
2 answers

If nameu secondnameare in the table students, try the following:

$students = User::where('type', '2')
     ->with(['details' => function ($query) use ($request) {

        if (!empty($request->name)) {
            $query->where('name', 'like', '%'.$request->name.'%');
            $query->orWhere('secondname', 'like', '%'.$request->name.'%');
        }

        $query->orderBy('name', 'desc');
    }])->get();

students (, $request->name, students ).

PS: @jedrzej.kurylo, orWhere, name secondname.

+1

, , (), , name , .

, , whereHas():

$students = User::whereHas('details', function ($query) use ($request) {            // Filter by name
        if (($term = $request->get("name"))) {
            $query->where('name', 'like', '%' . $term . '%');
            $query->where('secondname', 'like', '%' . $term . '%');
        }
    })
    ->join('details', 'details.user_id', '=', 'users.id')
    ->with("details")
    ->where('type', '2')
    ->orderBy('name', 'desc')
    ->get();

, , $term, :

  $query->where('name', 'like', '%' . $term . '%');
  $query->where('secondname', 'like', '%' . $term . '%');

  $query->where('name', 'like', '%' . $term . '%');
  $query->orWhere('secondname', 'like', '%' . $term . '%');
+1

Source: https://habr.com/ru/post/1653508/


All Articles