C
C
cron2018-03-22 14:37:04
Laravel
cron, 2018-03-22 14:37:04

How to add condition for nested relation in laravel?

Hello, there are following models:

class Page extends Model {
    protected $with = ['blocks'];

    public function blocks() {
        return $this->belongsToMany('App\Block');
    }
}

class Block extends Model {
    protected $with = ['fields'];

    public function fields() {
        return $this->hasMany('App\Fields');
    }
}

class Field extends Model {
    protected $with = ['data'];

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

And there is a controller in which I select the data:
public function get() {
    $page_id = 1;
    $data = Page::find($page_id);
}

As a result, I get the following structure:
Страница
    - Блок 1
        - Поле 1
            - Тестовые данные
        - Поле 2
            - Еще данные
    - Блок 2
        - Поле 1
            - Другие данные

A block can belong to multiple pages.
A particular field belongs to a particular block.
But the data stored in this field must be bound to the field and to the page at the same time .
That is, I need to pass the $page_id variable to the data () function of the Field model.
As a result, it would turn out something like this:
public function data() {
    return $this->hasOne('\App\Data')->where('page_id', '=', $page_id);
}

Tell me, please, how to do it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question