gpt4 book ai didi

php - 如何在 Laravel 4 中使用 `where` 方法和 `with` 方法?

转载 作者:行者123 更新时间:2023-12-04 04:39:40 25 4
gpt4 key购买 nike

鉴于以下非常简单的示例:

乡村类

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');
}
}

如何根据 id 列出所有状态或 name的国家。

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

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

最佳答案

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

class Country extends Eloquent {
public function states() {
return $this->hasMany('State', 'state_id');
}
}

$country = Country::find(1);
$states = $country->states()->get();

关于php - 如何在 Laravel 4 中使用 `where` 方法和 `with` 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19085139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com