在Laravel Eloquent中使用外键插入多个表

时间:2018-02-18 10:39:32

标签: php laravel-5.4 laravel-eloquent

这是我第一次使用laravel框架,到目前为止它的结构比我使用的其他框架好。但这些让我感到震惊,我已经调试了一段时间。 我有一个Post模型,有子模型Post Images和Post Location。我试图将数据插入到Post Images中,然后将保存数据的id保存到基本Model Post中,这样我就可以建立关系这些是我的代码 发布模型

class Post extends Model {
   protected $table = 'posts';
   public $primaryKey = 'id';
   public function user(){
    return $this->belongsTo('App\User');
   }
  public function post_image(){
    return $this->belongsTo('App\PostImage');
   }
  public function location(){
    return $this->belongsTo('App\PostLocation');
  }
}

从创建帖子迁移

 public function up(){
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('user_id')->unsigned();
        $table->integer('location_id')->unsigned();
        $table->integer('post_image_id')->unsigned();
        $table->timestamps();
    });

基本模型关系是

class PostImage extends Model{
   protected $table = 'post_images';
   public $primaryKey = 'id';
   public function post(){
    return $this->belongsTo('App\Post');
 }
}
class PostLocation extends Model{
   protected $table = 'location';
   public $primaryKey = 'id';
   public function post(){
    return $this->belongsTo('App\Location');
 }
}

在Post Controller存储方法中。我首先保存帖子图像,然后尝试引用插入的表ID作为外键,并在一段时间后发生错误我尝试不同的组合它不起作用。这些图像可以保存,但参考剂量可以正常工作

发布控制器商店代码

public function store(Request $request){
    $this->validate($request, [
     // Validation work here
    ]);
    // Function to save images work perfectly and return the an array containg image
    $images = $this->uploadAssetImages($request);
    $post= new Post();  
    $image = new PostImage();
    $image->image1 = $images[0];
    $image->image2 = $images[1];
    $image->image3 = $images[2];
    $image->save();//$image->id()
    //I have try these: $image_id = Response::json(array('success' => true, 'last_insert_id' => $image->id), 200);
    $asset->description = $request->input('description');
    $asset->user_id = auth()->user()->id;
    $asset->post_image()->save($image);// After debuging error is found here
    $asset->save();

希望这些可以解决吗?

0 个答案:

没有答案
相关问题