【问题标题】:How to use the `where` method along with the `with` method in laravel 4?如何在 laravel 4 中使用 `where` 方法和 `with` 方法?
【发布时间】:2013-09-30 01:15:22
【问题描述】:

给出以下非常简单的示例:

国家级

class Country extends Eloquent {
    protected $table = "countries";
    protected $fillable = array(
        'id',           
        'name'
    );

    public function state() {
        return $this->hasMany('State', 'country_id');
    }   
}

状态类

class State extends Eloquent {
    protected $table = "states";
    protected $fillable = array(
        'id',           
        'name',
        'country_id' #foreign
    );

    public function country() {
        return $this->belongsTo('Country', 'country_id');
    }
}

如何根据国家/地区的idname 列出所有州。

例子:

State::with('country')->where('country.id', '=', 1)->get()

上面返回一个区域,因为country 不是查询的一部分(Eloquent 必须稍后附加连接,在 where 子句之后)。

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    我认为你要么误解了这种关系,要么过于复杂化了。

    class Country extends Eloquent {
        public function states() {
            return $this->hasMany('State', 'state_id');
        }   
    }
    
    $country = Country::find(1);
    $states = $country->states()->get();
    

    【讨论】:

    • 我把它复杂化了!谢谢
    • 后续问题 - 使用 all 的任何方式。例如Country::all()->states()->get();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2014-10-11
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多