Laravel - When to use ->get()

后端 未结 5 1918
悲哀的现实
悲哀的现实 2021-02-07 03:06

I\'m confused as to when ->get() in Laravel...

E.G. DB::table(\'users\')->find(1) doesn\'t need ->get() to retrieve the results, neither

5条回答
  •  悲哀的现实
    2021-02-07 03:18

    Since the find() function will always use the primary key for the table, the need for get() is not necessary. Because you can't narrow your selection down and that's why it will always just try to get that record and return it.

    But when you're using the Fluent Query Builder you can nest conditions as such:

    $userQuery = DB::table('users');
    $userQuery->where('email', '=', 'foo@bar.com');
    $userQuery->or_where('email', '=', 'bar@foo.com');
    

    This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

    // Done with building the query
    $users = $userQuery->get();
    

提交回复
热议问题