Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GobssRuiz's avatar

Laravel query with two different model relationships

Guys, I need to put together a cute query. Where I have it return data from a relationship and data from another relationship.

There are 3 tables. Block, row and column.

A block has multiple rows and multiple rows have multiple columns.

So I need a query to just return these relationships.

I know I can do it with innerjoin, but it doesn't bring it in an organized way, I'll have to work with the json.

If you have a way to bring the json organized with the inner-join, it can be.

Well what I'm trying to do is this.

public function newOrder()
  {
    $form = Block::query();
    $form = $form->with('rows', 'Cols');
    $form = $form->get()->toArray();
    
    dd($form);

    return response()->json([
      'message' => 'success',
      'form' => $form,
    ], 200);

Model Block

public function rows(){
        return $this->hasMany(Row::class, 'block_id', 'id');
    }

Model row

public static function columns($el){
        return $el->hasMany(Column::class, 'row_id', 'id');
    }

The error here is clear. I'm getting a function inside the block model that doesn't exist. But how would I make this relationship between rows and columns in this query, doing it this way?

0 likes
2 replies

Please or to participate in this conversation.