php - Laravel Eloquent 关系获取记录到第三级关系

标签 php laravel eloquent

我有 users 表,它与 vendordetails 表有 hasOne 关系。

class User extends Authenticatable
{
    public function vendor_details() {
        return $this->hasOne('App\Vendordetail');
    }
}

另一方面 vendordetails 表包含 country_id、state_id 和 city_id,并且与 Country、State 和 City 模型具有 belongsTo 关系。

Vendordetail.php 模型是:-

class Vendordetail extends Model
{
    public $timestamps = false;

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

    public function this_state(){
        return $this->belongsTo('App\Country', 'state_id');
    }

    public function this_city(){
        return $this->belongsTo('App\Country', 'city_id');
    }

}

如果我查询用户表,我如何获取国家、州和城市的记录。

$user = User::with('vendor_details')->first();

在这个查询中它只找到 vendordetails 表的结果,我还想要国家、州和城市。

谢谢

最佳答案

访问嵌套关系

$user = User::with(['vendor_details.this_state','vendor_details.this_country','vendor_details.this_city'])->first();

关于php - Laravel Eloquent 关系获取记录到第三级关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39814470/

相关文章:

php - PHP 中是否有任何行继续符(& _)可用?

php - 如何使用PHP检查数据是否已经在数据库中?

Laravel 4.1 Eloquent - 使用 whereHas 的自定义连接

laravel - 未添加验证用户

php - 如何从 codeigniter 中的 URL 获取 id?

javascript - 增量按钮在 magento 中无法正常工作

php配置-服务器错误网站在检索时遇到错误

php - Laravel 5.3 - 限制登录尝试默认 auth-Trait 方法 hasTooManyLoginAttempts 尚未应用

php - 不知道如何在 laravel 中管理这个数据库现实

php - Laravel Eloquent : getting id field of joined tables in Eloquent