Relationship between tables
Create the father table
- php artisan mak:mig create_migration_card_table --create=cards
Create the child table
- php artisan mak:mig create_migration_card_table --create=notes
Relationship
Create the foreign key in the child table
- $table->integer('card_id')->unsigned()->index();
Create the Model
- php artisan make:model Note
- php artisan make:model Card
Shortcut
In this way we can create the model and the migration at the same time
- php artisan make:model <Class> -m
Refresh DB
- php artisan migrate:refresh
Using Eloquent
In the father class (Model) add a method to get the childs
- public function notes(){
- return $this->hasMany( <Class>::class );
- }
In the child class (Model) add the next method to get the father
public function card(){
return $this->belongsTo(Card::class);
}
With this method we can relate a child more easily in tinker as:
- $card->notes()->save($note);
Using Tinker
Get in a variable the registers of a table- $card = App\Card::first();
Get all the results and then get the first
- $card->notes->first();
Get the first result
- $card->notes()->first();
Display the SQL commands that internally use tinker
- DB::listen( function($query) { var_dump($query->sql); } ) ;
- Use fresh() if the query has been done due to Tinker save the query
- $card->fresh()->notes->first();
Comentarios
Publicar un comentario