【问题标题】:How to use join using One-to-Many relationship in Laravel Eloquent?如何在 Laravel Eloquent 中使用一对多关系连接?
【发布时间】:2018-06-08 16:26:52
【问题描述】:

我有两张桌子countrystate。 country 表包含country_idcountry_name 列。 状态表包含state_idstate_namecountry_id 列。

我想在输出中显示state_idstate_namecountry_name

Country模特:

class Country extends Model
{
    protected $table = 'country';
    protected $fillable = ['country_name'];
    public $timestamps = false;
    protected $primaryKey = 'country_id';

    public function state()
    {
        return $this->hasMany(State::class);
    }
}

State模特:

class State extends Model
{
    protected $table = 'state';
    protected $fillable = ['state_name','country_id'];
    public $timestamps = false;
    protected $primaryKey = 'state_id';

    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}

我的StateController 是:

$country_state_data = State::with('country_name')->get();

【问题讨论】:

  • 我编辑了您的问题并更改了一些类名的大小写。请确保您确实使用PascalCase 作为类名(即首字母大写和每个单词的首字母大写,即StateController)。您的代码中存在一些不一致,这将导致警告。

标签: laravel eloquent foreign-keys relational-database laravel-5.5


【解决方案1】:

你已经快到了。您要做的是使用State::get() 获取所有状态的列表。然后在get() 之前添加with('country'),以便将其添加到查询生成器中。如您所见,country 是您想要预先加载的关系的名称。之后,您可以访问 country 的所有属性,就像访问 state 的属性一样:

$states = State::with('country')->get();
foreach ($states as $state) {
    echo "ID: {$state->id}, State: {$state->name}, Country: {$state->country->name}";
}

会输出类似的东西

ID: 1, State: Vorarlberg, Country: Austria
ID: 2, State: Bavaria, Country: Germany

经过一番调查,似乎在更改主键时,将键添加到关系定义中是有意义的:

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

否则,关系将无法正确加载。

【讨论】:

  • 只有 {$state->country_id 有效,但 $state->country_name 无效。
  • 因为country_id 是一个外键并且存在于state 表中。如果你想要country_name,你必须使用{$state->country->country_name}。这就是为什么你不使用类名作为每列的前缀的原因——它读起来不太好。当您阅读{$state->country->name} 时,它会更有意义,对吧?
  • {{ $state->country->country_name }},这会产生错误;尝试获取非对象的属性
  • 是否有可能不是您的所有州都分配了(有效country_id
  • 我检查了,状态表中的行具有有效的 country_id,如果我在数据库上运行此查询,它工作正常。 SELECT state_id,state_name,country_name FROM country,state WHERE country.country_id=state.country_id
【解决方案2】:

使用

$country_state_data = state::with('country')->get();

在你看来

@foreach($country_state_data as $state)
    {{ $state->country->country_name }}
@endforeach

【讨论】:

  • 这不是返回国家名称。我也想显示国家名称。
  • {{ $state->country->country_name }},这会产生错误;尝试获取非对象的属性
猜你喜欢
  • 1970-01-01
  • 2016-02-11
  • 2013-02-09
  • 1970-01-01
  • 2017-04-20
  • 2021-04-21
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多