Laravel assignToMany.belongsTo вложенный запрос отношений, где дочерний столбец = родительский идентификатор - PullRequest
0 голосов
/ 19 сентября 2019

У меня есть две модели (и таблицы базы данных с соглашениями об именах Laravel), и я пытаюсь добиться загрузки Collections с Equipment и Equipment.collection_meters, где collection_meter равно Collection.id.

Как получить доступ к collections.id в дочерних отношениях $query->with?

или

Как получить доступ к equipment.pivot.collection_id в дочерних отношениях$query->with?

Вот мои модели ...

class Collection extends Model {
    public function equipment() {
        return $this->belongsToMany(Equipment::class, 'collection_equipment', 'collection_id', 'equipment_id')->withTimestamps();
    }
}

class CollectionMeter extends Model {
    public function equipment() {
        return $this->belongsTo(Equipment::class); 
    }
}

class Equipment extends Model {
    public function collection_meters() {
        return $this->hasMany(CollectionMeter::class)->latest(); // ->currentStatus('active')
    }
}

equipment_id столбец находится в таблице collection_meters

Вот код, который я пробовал, но я просто не могу получить Collection.id в запросе дочерних отношений.Если я опускаю ребенка $query->where, я получаю ALL из equipment.equipment_meters.

$collections = Collection::with([
    'equipment',
    'equipment.collection_meters' => function($query) {
        $query->where('collection_meters.collection_id', '=', 'collections.id');
    }
])
->get();

Я пробовал их вместо 'collections.id' с тем же результатом 'equipment.pivot.collection_id' 'equipment.collection_id'

Я вижу это в [equipment] => Array, могу ли я как-то получить доступ к [collection_id] => 2 в $query->where?

[pivot] => Array
    (
        [collection_id] => 2
        [equipment_id] => 1
        [created_at] => 2019-09-17 00:17:00
        [updated_at] => 2019-09-17 00:17:00
    )

Результаты без$query->with ([collection_meters] имеет ВСЕ)

Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Name of Collection
            [operator_id] => 1
            [location_id] => 4
            [account_id] => 1
            [date_time] => 2019-09-16 04:41:26
            [reconciliation_id] => 
            [created_by_id] => 1
            [updated_by_id] => 1
            [created_at] => 2019-09-16 23:44:43
            [updated_at] => 2019-09-18 17:32:53
            [equipment] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => Name of Equipment
                            [ims_identifier] => AFA-64
                            [operator_identifier] => 073076-01
                            [equipment_model_id] => 1
                            [operator_id] => 1
                            [location_id] => 4
                            [created_by_id] => 1
                            [updated_by_id] => 1
                            [created_at] => 2019-07-17 13:17:28
                            [updated_at] => 2019-08-14 00:04:07
                            [pivot] => Array
                                (
                                    [collection_id] => 2
                                    [equipment_id] => 1
                                    [created_at] => 2019-09-17 00:17:00
                                    [updated_at] => 2019-09-17 00:17:00
                                )

                            [collection_meters] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 17
                                            [equipment_meter_id] => 1
                                            [value] => 0.25
                                            [gross] => 25.00
                                            [refund] => 2.00
                                            [test] => 2.00
                                            [reading_start] => 72985
                                            [reading_end] => 73085
                                            [collection_id] => 3
                                            [equipment_id] => 1
                                            [operator_id] => 1
                                            [location_id] => 4
                                            [account_id] => 1
                                            [created_by_id] => 1
                                            [updated_by_id] => 1
                                            [created_at] => 2019-09-17 18:23:41
                                            [updated_at] => 2019-09-17 22:56:50
                                        )

                                    [1] => Array
                                        (
                                            [id] => 9
                                            [equipment_meter_id] => 1
                                            [value] => 0.25
                                            [gross] => 24.00
                                            [refund] => 2.00
                                            [test] => 1.00
                                            [reading_start] => 72885
                                            [reading_end] => 72985
                                            [collection_id] => 2
                                            [equipment_id] => 1
                                            [operator_id] => 1
                                            [location_id] => 4
                                            [account_id] => 1
                                            [created_by_id] => 1
                                            [updated_by_id] => 1
                                            [created_at] => 2019-09-17 00:17:00
                                            [updated_at] => 2019-09-18 17:32:53
                                        )

                                    [2] => Array
                                        (
                                            [id] => 1
                                            [equipment_meter_id] => 1
                                            [value] => 0.25
                                            [gross] => 282.50
                                            [refund] => 3.26
                                            [test] => 0.00
                                            [reading_start] => 71755
                                            [reading_end] => 72885
                                            [collection_id] => 1
                                            [equipment_id] => 1
                                            [operator_id] => 1
                                            [location_id] => 4
                                            [account_id] => 1
                                            [created_by_id] => 1
                                            [updated_by_id] => 1
                                            [created_at] => 2019-09-11 22:38:31
                                            [updated_at] => 2019-09-11 22:38:31
                                        )

                                )

                        )

Результаты с $query->with ([collection_meters] пусто)

Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Name of Collection
            [operator_id] => 1
            [location_id] => 4
            [account_id] => 1
            [date_time] => 2019-09-16 04:41:26
            [reconciliation_id] => 
            [created_by_id] => 1
            [updated_by_id] => 1
            [created_at] => 2019-09-16 23:44:43
            [updated_at] => 2019-09-18 17:32:53
            [equipment] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => Name of Equipment
                            [ims_identifier] => AFA-64
                            [operator_identifier] => 073076-01
                            [equipment_model_id] => 1
                            [operator_id] => 1
                            [location_id] => 4
                            [created_by_id] => 1
                            [updated_by_id] => 1
                            [created_at] => 2019-07-17 13:17:28
                            [updated_at] => 2019-08-14 00:04:07
                            [pivot] => Array
                                (
                                    [collection_id] => 2
                                    [equipment_id] => 1
                                    [created_at] => 2019-09-17 00:17:00
                                    [updated_at] => 2019-09-17 00:17:00
                                )

                            [collection_meters] => Array
                                (
                                )

                        ) ...

Ожидаемые результаты ([collection_meters] имеет [id] => 2 равно [collection_id] => 2)

Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Name of Collection
            [operator_id] => 1
            [location_id] => 4
            [account_id] => 1
            [date_time] => 2019-09-16 04:41:26
            [reconciliation_id] => 
            [created_by_id] => 1
            [updated_by_id] => 1
            [created_at] => 2019-09-16 23:44:43
            [updated_at] => 2019-09-18 17:32:53
            [equipment] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => Name of Equipment
                            [ims_identifier] => AFA-64
                            [operator_identifier] => 073076-01
                            [equipment_model_id] => 1
                            [operator_id] => 1
                            [location_id] => 4
                            [created_by_id] => 1
                            [updated_by_id] => 1
                            [created_at] => 2019-07-17 13:17:28
                            [updated_at] => 2019-08-14 00:04:07
                            [pivot] => Array
                                (
                                    [collection_id] => 2
                                    [equipment_id] => 1
                                    [created_at] => 2019-09-17 00:17:00
                                    [updated_at] => 2019-09-17 00:17:00
                                )

                            [collection_meters] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 9
                                            [equipment_meter_id] => 1
                                            [value] => 0.25
                                            [gross] => 24.00
                                            [refund] => 2.00
                                            [test] => 1.00
                                            [reading_start] => 72885
                                            [reading_end] => 72985
                                            [collection_id] => 2
                                            [equipment_id] => 1
                                            [operator_id] => 1
                                            [location_id] => 4
                                            [account_id] => 1
                                            [created_by_id] => 1
                                            [updated_by_id] => 1
                                            [created_at] => 2019-09-17 00:17:00
                                            [updated_at] => 2019-09-18 17:32:53
                                        )

                                )

                        )

1 Ответ

0 голосов
/ 20 сентября 2019

Какие отношения вы используете?«Много ко многим» или «Один ко многим»?Если у вас есть три таблицы, одна из которых "сводная", вы должны определить в обеих моделях взаимосвязь asToMany:

class Collection extends Model {

    public function equipments() {
        return $this->belongsToMany(Equipment::class, 'collection_equipment', 
        'collection_id', 'equipment_id')->withTimestamps();
    }
}

Как называется сводная таблица?коллекция_оборудование?Как ваша структура?

collection => collection_equipment <= equipments </p>

class Equipment extends Model {

    public function collections() {
       return $this->belongsToMany(Collection::class, 'collection_equipment', 
       'equipment_id', 'collection_id')->withTimestamps();
    }
}

Где находится столбец collection_meters?В таблице оборудований?

Тогда, если вы хотите получить информацию о вложенных таблицах, просто:

$collections = Collection::with('equipments')->get();

Но иногда вы хотите получить информацию, используя сводную модель:

class CollectionEquipment extends Model {

    protected $table = 'collection_equipment';

    public function collection() {
       return $this->belongsTo(Collection::class, 'collection_id');
    }

    public function equipment() {
       return $this->belongsTo(Equipment::class, 'equipment_id');
    }

}

Тогда просто:

$collections = CollectionEquipment::with(['equipment', 'collection'])
               ->get();

Поскольку вы уже определили collection_id и equipment_id во всех классах модели, вам не нужно отображать их в запросе, как если бы вы использовали 'join'

...