Laravel 4 - An eloquent way to attach a where clause to relationships when creating a collection

This may be a hoax, but I spent some time looking for the right answer to this question and have not yet found it.

Thus, essentially, all I want to do is join the two tables and bind the where clause to the whole collection based on the field from the joined table.

So let's say I have two tables:

users:
   -id
   -name
   -email
   -password
   -etc

user_addresses:
   -address_line1
   -address_line2
   -town
   -city
   -etc

For argumentation (the implementation of this may not be the best example) - suggests that the user may have several address entries. Now laravel / eloquent gives us a good way to wrap conditions in a collection as regions, so we will use one of them to define a filter.

, smallville, :

Users.php()

class users extends Eloquent{
    public function addresses(){
        return $this->belongsToMany('Address');
    }

    public function scopeSmallvilleResidents($query){
        return $query->join('user_addresses', function($join) {
                    $join->on('user.id', '=', 'user_addresses.user_id');
                })->where('user_addresses.town', '=', 'Smallville');
    }
}

, , , , , .

, , , :

// , , ,

User::with(array('Addresses' => function($query){
                $query->where('town', '=', 'Smallville');
            }));

//

User::with('Addresses')->where('user_addresses.town', '=', 'Smallville');

, "" , ? , Eloquent , ?

. , , (, ), , , .

.

+4
2

, . , Users, user_address.town = 'Smallwille' .

, , , ( ).

, :

$products = array();
$categories  = Category::where('type', 'fruit')->get();
foreach($categories as $category)
{
 $products = array_merge($products, $category->products);
}
return $products;
+2

, , . :

$addressFilter = Addresses::with('Users')->where('town', $keyword)->first(); $users= $addressFilter->users;

, .

///* , - , , 'with'

$usersFilter = Addresses::with(array('Users' => function($query) use ($keyword){ 
        $query->where('somefield', $keyword);
    }))->where('town', $keyword)->first();
$myUsers = $usersFilter->users;
+1

All Articles