我的应用程序中有 2 个表。products
和product_metas
。两者都One-To-One Relationship
成立了。
我正在使用laravel-excel插件作为我products
和product_metas
表的导入和导出的解决方案。
现在,导出功能完全可以正常工作,没有任何问题。但是导入没有按我想要的方式工作。
这是用于导入的控制器方法:
public function postImportProducts(Request $request) {
Excel::load( $request->file( 'productsFile' ), function ( $reader ) {
$reader->each( function ( $sheet ) {
if ( $sheet->getTitle() === 'Product-General-Table' ) {
$sheet->each( function ( $row ) {
echo $row->name . '<br />'; // <-- outputs the name correctly.
DB::statement( 'SET FOREIGN_KEY_CHECKS=0;' );
DB::table( 'products' )->truncate();
$product = new Product;
$product->name = $row->name;
$product->amount = $row->amount;
$product->save();
DB::statement( 'SET FOREIGN_KEY_CHECKS=1;' );
});
}
if ( $sheet->getTitle() === 'Product-Meta-Table' ) {
$sheet->each( function ( $row ) {
DB::statement( 'SET FOREIGN_KEY_CHECKS=0;' );
DB::table( 'product_metas' )->truncate();
$productMeta = new ProductMeta;
$productMeta->product_id = $row->product_id;
$productMeta->description = $row->description;
$productMeta->title = $row->title;
$productMeta->keywords = $row->keywords;
$productMeta->save();
DB::statement( 'SET FOREIGN_KEY_CHECKS=1;' );
});
}
});
});
}
我不知道是什么错误,但我得到以下信息ErrorException
:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into `products` (`name`, `amount`, `updated_at`, `created_at`) values (, , 2015-07-16 09:18:02, 2015-07-16 09:18:02))
编辑1:
产品型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* Properties that are mass assignable
*
* @var array
*/
protected $fillable = ['name', 'amount'];
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function meta()
{
return $this->hasOne('App\ProductMeta');
}
}
产品元模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProductMeta extends Model
{
protected $fillable = ['product_id', 'title', 'description', 'keywords'];
public function product()
{
return $this->belongsTo('App\Product');
}
}
请帮我解决这个问题。