Laravel 4 - How to use where conditions for relation's column

后端 未结 2 1703
[愿得一人]
[愿得一人] 2021-02-09 14:31

This is what I want, I have two tables. one is \'Restaurants\' and other is \'Facilities\'.

The tables are simple.. and One-To-One relations. like there is a restaurant

相关标签:
2条回答
  • 2021-02-09 15:01

    You can use where and other sql-based methods on the relationship objects.

    That means you can either create a custom method in your model:

    class Restaurant extends Eloquent {
    
        protected $table = 'restaurants';
    
        public function facilities($wifi) {
            return $this->belongsTo('Facility')->where('wifi', '=', $wifi);
        }
    }
    

    Or you can try to use query scopes:

    class Restaurant extends Eloquent {
    
        protected $table = 'restaurants';
    
        public function facility() {
            return $this->belongsTo('Restaurant');
        }
    
        public function scopeFiltered($query, $wifi)
        {
            return $query->where('wifi', '>', 100);
        }
    }
    

    Then:

    $wifi = 1;
    $restaurants = Restaurant::facilities()->filtered($wifi)->get();
    

    This isn't exactly what you need likely, but query scopes is likely what you want to use to get what you're attempting.

    THe key point is to know that relationship classes can be used like query builders - for example:

    $this->belongsTo('Facility')->where('wifi', '=', $wifi)->orderBy('whatever', 'asc')->get();
    
    0 讨论(0)
  • 2021-02-09 15:10

    There are some ways to filter both, this is using QueryBuilder:

    Restaurant::join('facilities','facilities.restaurant_id','=','restaurants.id')
                    ->where('name','bbq')
                    ->where('facilities.wifi','!=', 1)
                    ->get();
    
    0 讨论(0)
提交回复
热议问题