【问题标题】:how to connect multiple tables with Laravel models如何使用 Laravel 模型连接多个表
【发布时间】:2020-12-12 03:59:43
【问题描述】:

我正在使用 Laravel 7。 我想检索所有活跃且属于奥地利的用户。 我想使用 laravel 关系来做到这一点。 应该通过模型连接三个表:countriesusersuser_details

Country.php:

public function user_details()
{
    return $this->hasMany('App\UserDetail', 'citizenship_country_id', 'id');
}

User_detail.php:

public function country()
{
    return $this->belongsTo('App\Country', 'citizenship_country_id', 'id');
}

public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

用户.php:

public function user_detail()
{
    return $this->hasOne('App\UserDetail', 'user_id', 'id');
}

在控制器中,我使用以下代码检索所有活跃的奥地利用户:

return Country::where('name', 'Austria')->first()->user_details()->first()->user()->where('active', '1')->get();

我应该想象两个用户,但我只得到一个用户。我想错误是第二个first

可以帮忙吗?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    试试这个。

    $users = User::whereHas('user_details.country', function ($query) { 
        $query->where('countries.name', "Austria"); 
    })
    ->where("active",1)
    ->get();
    
    

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 2016-03-29
      • 2019-10-04
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 2018-07-03
      相关资源
      最近更新 更多