C
C
cron2018-03-21 14:14:52
Laravel
cron, 2018-03-21 14:14:52

How to create a nested relation in laravel that selects an entity by two fields?

Hello.
I have the following entities on my site:
Page - Page, for example "contacts"
id, name
Block is connected to the page, through the relation belongsToMany('App\Block')
Block - Block, for example "seo"
id, name
Fields are connected to the block, via hasMany('\App\Field');
Field - Field, for example "keywords" and "description",
id, block_id, name
One block can be connected to different pages and different data must be loaded into it.
To do this, I want to make another Data entity, which will store the data of the block fields:
field_id, page_id, value
I'm trying to select a page with something like the following query:
$ data = Page::
But at the same time, I do not understand how to create a relation for loading data.
To select them, you need to set two conditions: field id and page id
Tell me, what relation can be applied to create such a selection?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Melnik, 2018-03-29
@Gesparo

Page::with(['data', 'data.field']->find(42);
where data

function data() {
  return $this->hasMany('App\Data');
}

and data.field and data.block are in Data model
function field() {
  return $this->hasOne('App\Field');
}

You can also add block_id to the data table for convenience and pull it out as with the field function
In my opinion, correct me if I'm wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question