A, joint table query

There must be at least two tables (except the table itself join itself, autolink query), and there is a relationship between two tables. For example, you can create two tables: article table and author table.

Article table:

id A primary key
Article_name Article name, vARCHar (50), not null
Author_id Author ID, int, not null

Author table:

id A primary key
Author_name Author name, varchar(20), not null

1.1 Creating a Migration File

php artisan make:migration create_article_table php artisan make:migration create_author_table articleAdd field:

$table->increments('id');
$table->string('article_name'.50)->comment('Article Title');
$table->integer('author_id') -> comment('the author id');
$table->timestamps();
Copy the code


Author + field:

$table->increments('id');
$table->string('author_name'.20) -> comment('Author name');
$table->timestamps();
Copy the code


1.2 Migrating Files

Then perform the migration file:php artisan migrate

1.3 Simulated data (through filler)

1. Create a fill file (can write multiple data table writes together)php artisan make:seeder ArticleAndAuthorTableSeeder 2. Write code for data simulation3. Execute the fillerphp artisan db:seed --class=ArticleAndAuthorTableSeeder

1.4 Example for querying a union table

Request to query the data table (article table, author table), query the information of the article contains the name of the author, a joint table query has a total: inner table, left table, right table.

SQL > select * from left;select article.id,article.article_name, author.author_name from article left join author on article.author_id = author.id

Change the above SQL statement to a chained operation:

Syntax: DB facade/model -> join join table mode name (associated table name, table 1 field, operator, table 2 field)

Left link: If you want to executeThe left linkRather thanIn the linkYou can useleftJoinMethod, the method andjoinMethod to create a route:Create method:Effect:

If you find this article helpful on your way to learning PHP, please follow me to like and comment on it. Thank you, your blog is definitely another support for me to write.