I'm new for laravel, I try to learn from http://ift.tt/1LRcx0L
when I run from cmd php artisan tinker -> $article->tags()->attach(1)
get an error:
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'article_id' cannot be null (SQL: insert into `article_tag` (`article_id`, `tag_id`) values (, 1))'
article_id value is NULL. I don't understand why article_id always null??
Article.php (app\Article.php):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $fillable = array('title', 'body', 'published_at');
/*
* Get the tags associated with the given article
*/
public function tags(){
return $this->belongsToMany('App\Tag');
}
}
Tag.php (app/Tag.php):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $fillable = array('name');
/*
* Get the articles associated with the given tag
*/
public function articles(){
return $this->belongsToMany('App\Article');
}
}
migration create_articles_table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->dateTime('published_at');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('articles');
}
}
migration create tags and article_tag:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->timestamps();
});
Schema::create('article_tag', function (Blueprint $table) {
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tags');
Schema::drop('article_tag');
}
}
and I don't know where is my mistake. Thank's for your help..
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1rjDDHS
via IFTTT
Aucun commentaire:
Enregistrer un commentaire