在Laravel Eloquent创建方法中,我无法将数据保存在数据库中

时间:2017-11-29 16:25:21

标签: php laravel laravel-5 eloquent

我有三种模式:

  • Language
  • Article
  • Category

Article表有两个外键category_idLanguage_id。语言模型与文章模型具有“一对多”的关系,类似的模型与文章模型具有“一对多”的关系。

我的Category型号:

class Category extends Model
            { 

            protected $fillable = [
                 'category_name', 
            ];

            public function articles(){

                return $this->hasMany('App\Article');
             }
           }

我的Language型号:

class Language extends Model
    {
         protected $fillable = [
            'language_name'
        ];

         public function articles(){

            return $this->hasMany('App\Article');
        }

    }

我的Article型号:

class Article extends Model
{
 protected $fillable = [

   'language_id','category_id','category_name','article_title',
   'article_desc','source_from','source_url','video_link',
   'audio_url','author_name','article_image_url','like_count'
    ];

    public function languages(){

        return $this->belongsTo('App\Language');
    }

    public function categories(){

        return $this->belongsTo('App\Category');
    }

}

如何使用Laravel Eloquent在数据库中插入?

 $Article = new Article (
                 [
                   'article_image_url' => $img_url ,
                   'audio_url' => $audio_url,
                   'category_name'=>$category_name ,
                   'article_title'=>$request->article_title,
                   'article_desc'=>$request->article_desc,
                   'source_from'=>$request->source_from,
                    'source_url'=>$request->source_url,
                    'video_link'=>$request->video_link,
                    'author_name'=>$request->author_name,
                    'like_count'=>'0',

                  ]
            );

            $language = new Language;
            $category = new Category;
            $language->articles()->save($Article);

language_id没有默认值;这是外键。

0 个答案:

没有答案