在 Laravel 中:如何通过 4 个相关表的预加载获取特定列?

In Laravel: How to get specific columns with eager loading for 4 related tables?

假设我有接下来 4 个相关的 tables:

countries
---------
(PK) id
country_name
...

cities
------
(PK) id
(FK) country_id
city_name
...

districts
---------
(PK) id
(FK) city_id
district_name
...

areas
-----
(PK) id
(FK) district_id
area_name
...

并且假设我想获得所有国家的城市属于每个国家,地区属于每个城市,地区属于每个地区,我只想从每个 table.如何在 Laravel 中使用预加载来做到这一点?

首先,您需要像这样在模型中设置这些表之间的关系:

// in models/Country.php file (countries model)

/**
 * City relationship
 */
public function cities()
{
    return $this->hasMany('City');
}

// in models/City.php file (cities model)

/**
 * Country relationship
 */
public function country()
{
   return $this->belongsTo('Country');
}


/**
 * District relationship
 */
public function districts()
{
    return $this->hasMany('District');
}

// in models/District.php file (districts model)

/**
 * City relationship
 */
public function city()
{
   return $this->belongsTo('City');
}


/**
 * Area relationship
 */
public function areas()
{
    return $this->hasMany('Area');
}

// in models/Area.php file (areas model)

/**
 * District relationship
 */
public function district()
{
   return $this->belongsTo('District');
}

最后,您可以在任何控制器中使用下一个代码来获取所需的数据:

    $countries = Country::with([
        "cities" => function($q1) {
            $q1->with([
                "districts" => function($q2) {
                    $q2->with([
                        "areas" => function($q3) {
                            $q3->select(["id", "district_id", "area_name"]) // columns that you want to get from areas table
                                ->where("id", ">", 1)
                                ->orderBy("id", "asc");
                        }
                    ])
                    // You must always select the foreign key or the primary key of the relation
                    // otherwise Laravel won't be able to link the models together
                    ->select(["id", "city_id", "district_name"]) // columns that you want to get from districts table
                    ->where("id", ">", 5)
                    ->orderBy("id", "asc");
                }
            ])
            // You must always select the foreign key or the primary key of the relation
            // otherwise Laravel won't be able to link the models together
            ->select(["id", "country_id", "city_name"]) // columns that you want to get from cities table
            ->where("id", ">", 10)
            ->orderBy("id", "asc");
        },
    ])
    ->select(["id", "country_name"]) // columns that you want to get from countries table
    ->where("id", ">", 15) // in case you have a condition
    ->orderBy("id", "asc") // in case you want to order results
    ->get();

    return $countries;

请注意,您必须始终 select 关系的外键或主键,否则 Laravel 将无法 link 模型。