1

For example I have 3 tables:

Table A:
id 
name
Table B
id
name
tableA_id
Table C
id 
name
tableB_id

and I need to display all data from Table A in table and name from Table C like that:

id | name | TableC name

I can write code for get name of tableC like that:

        $data = DB::table('tableA')
            ->join('tableB','tableB.tableA_id','=','tableA.id')
            ->join('tableC','tableC.tableB_id','=','tableC.id')
            ->select('tableA.id','tableA.name','tableC.name')
            ->get();

But if I want to display more data, what would appropriate solution to solve this without making query huge and seperate it somehow to make it simple to display in blade?

justsimpleuser
  • 149
  • 1
  • 14
  • 1
    you can use `database_view` use this link https://www.w3schools.com/sql/sql_view.asp and use `sqlyog` app to create a database view in `WIZARD` – Reza sh Jan 25 '20 at 08:32

1 Answers1

1

Simply use HasMany relation, thou you naming is inconsistent with the Laravel standard, if you name your tables in plural form of your model, you can avoid defining $table = 'a'. Your foreign key is not also the standard, you can avoid the second parameter of has many if they are named probably, example table b a_id. Read this post on it

class A {
    protected $table = 'a';

    public function bs() {
        return $this->hasMany(B::class, 'tableA_id');
    }
}

class B {
    protected $table = 'b';

    public function cs() {
        return $this->hasMany(C::class, 'tableB_id');
    }
}

class C {
    protected $table = 'c';
}

The naming is weird in this example, as it is very inconvenient to make plural version of A, B and C tables.

When you want to access the C relation, you can do it like this, you but relations can have multiple so described how that is gonna work.

$a = A::find(1);
$cName = $a->bs->first()->cs->first()->name;
mrhn
  • 17,961
  • 4
  • 27
  • 46