下午好。在laravel 5.0中,我在主机上创建两个表的关系时遇到了一个小问题。
我的产品迁移表:
<?php
use Illuminate'Database'Schema'Blueprint;
use Illuminate'Database'Migrations'Migration;
class CreateProductsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function(Blueprint $table)
{
$table->increments('id');
$table->string('name', 255);
$table->string('slug');
$table->text('description');
$table->string('extract', 300);
$table->decimal('price', 8, 2);
$table->string('quantity', 300);
$table->string('image', 300);
$table->boolean('visible');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')
->references('id')
->on('categories');
$table->integer('brand_id')->unsigned();
$table->foreign('brand_id')
->references('id')
->on('brands');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('products');
}
}
我的产品型号:
<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['name', 'slug', 'description', 'extract', 'price', 'quantity', 'image', 'visible', 'category_id', 'brand_id'];
// Relation with Category
public function category()
{
return $this->belongsTo('App'Category');
}
// Relation with Brand
public function brand()
{
return $this->belongsTo('App'Brand');
}
/*public function upload()
{
return $this->hasOne('App'Upload');
}*/
//Query para buscador
public function scopeName($query, $name)
{
//dd("scope: " . $name);
$query->where('DB::raw("CONCAT(name, '', description, '', price, '', quantity)"), "LIKE", "%$name%");
}
}
我的类别模型:
<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
public $timestamps = false;
//Query para buscador
public function scopeName($query, $name)
{
//dd("scope: " . $name);
$query->where('DB::raw("CONCAT(name)"), "LIKE", "%$name%");
}
}
我的品牌模型:
<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Brand extends Model
{
protected $table = 'brands';
protected $fillable = ['name'];
public $timestamps = false;
public function products()
{
return $this->hasMany('App'Product');
}
//Query para buscador
public function scopeName($query, $name)
{
//dd("scope: " . $name);
$query->where('DB::raw("CONCAT(name)"), "LIKE", "%$name%");
}
}
当我运行迁移时,生成以下错误消息:
Migration table created successfully.
[Illuminate'Database'QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `products` add constraint products_brand_id_foreign foreign k
ey (`brand_id`) references `brands` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
谁能帮我?
感谢合作,通过回复解决问题:
etherg, Hilmi Erdem KEREN