skip to Main Content

I’m trying to select a specific column from a relationship.

F.x

User::with(array('phone' => function($q) {
 $q->where('ext', "!=" 42);
}))->select('id', 'number');

Here i ONLY want to select the user ID, and the number for the phone.

How can i do that?

Keep in mind, there is over 2m users and 100m numbers, which is why i only want the user id and the number.

3

Answers


  1. Please try:

    User::with(array('phone' => function($q) {
     $q->where('ext', "!=", 42);
     $q->select('id', 'number');
    }));
    

    Or

    User::with('phone:id,number')->get();
    
    Login or Signup to reply.
  2. You can achieve this by making use of the select method within your with clause, specifying only the columns you are interested in. Additionally, you might need to add the foreign key to the select method to preserve the relationship linkage.

    For your specific case, your Eloquent query should look something like this:

    User::with(['phone' => function($q) {
        $q->where('ext', '!=', 42)
          ->select('id', 'number', 'user_id'); // Add user_id here, it's essential for Eloquent to make the link
    }])
    ->select('id')
    ->get();
    

    In this query, id, number, and user_id in the select method of the phone relationship are the columns from the phones table, while the id in the select method outside the with clause is from the users table.

    Note that it’s essential to include the foreign key (user_id) in the select method within the with clause. This is because Eloquent needs this to match the related models back onto their parent models.

    Also, remember that the with method does eager loading, which means it will fetch all related phones that meet the criteria for all users, not just the first one that matches.

    If you’re working with very large datasets, it might be more efficient to consider database indexing strategies, using chunks or even directly using a JOIN with a raw query. These can all be done within Laravel, and might be better suited for your use case, depending on your exact needs.

    Login or Signup to reply.
  3. User::with(array('phone' => function($q) {
        $q->where('ext', '!=', 42)->select('id', 'number');
    }))
    ->select('users.id', 'phone.number')
    ->get();
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search