Home > Mobile >  Laravel join with count
Laravel join with count

Time:09-22

can anyone help me with Laravel join with count I’m trying to get the laravel to join with a count of three tables where table 1 one is a relationship with table 2 and table 3 Which display data of table1 and table and the count value of table three only with a relationship with table1

Table name: table1

Id name

1 a1

2 a2

3 a3

table name : table2

id 2name table1_id

1 b1 1

2 b2 2

3 b3 3

table name: table3

id 3name table1_id

1 c1 1

2 c2 1

3 c3 2

4 c4 2

4 c5 3

Output need

Name 2name count3name

a1 b1 2

a2 b2 2

a3 b3 1

CodePudding user response:

Your best bet would be to setup a relationship for table2 and table3 in your table1 model. When you do that you can use the relationship to get the count. For example, you'd have something like this in your table1 model:

public function table3()
{
    return $this->hasMany(Table3::class);
}

Then in your view, you'd just echo $table1->table3->count()

Check out the relationship docs: https://laravel.com/docs/8.x/eloquent-relationships

  • Related