Blog和Category之间有很多关系。
blog.php的
public function category() {
return $this->belongsToMany('App\Category');
}
Category.php
public function blog() {
return $this->belongsToMany('App\Blog');
}
create_blogs_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->length(250);
$table->text('content');
$table->integer('updated_by')->unsigned()->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('blogs');
}
}
create_categories_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->length(250);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
blog_category_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BlogCategoryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create ( 'blog_category', function (Blueprint $table) {
$table->integer ( 'category_id' )->unsigned ();
$table->integer ( 'blog_id' )->unsigned ();
$table->foreign ( 'category_id' )->references ( 'id' )->on ( 'categories' );
$table->foreign ( 'blog_id' )->references ( 'id' )->on ( 'blogs' );
$table->primary ( [
'category_id',
'blog_id'
]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists ( 'blog_category' );
}
}
要获得与我可以编码的任何类别相关的博客
$category = App\Category::find(1);
$category->blog->get();
但是,如果我想获得与类别ID为1&amp;的类别相关的博客2在一个查询中。应该解决这个问题的方法是什么?
我尝试了同样的方法,它给我的错误就像 '带有消息的异常'此属性[博客]在此集合实例上不存在。'