Laravel / ORM不会创建相关表

时间:2016-06-02 07:05:42

标签: php laravel orm eloquent relation

如何为ORM相关变量添加值

它包含新闻和评论模型

class News extends Model {

protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'news';
protected $fillable = array(
    'id',
    'name',
    'category',
    'type',
    'datetime',
    'shortdesc',
    'desciption'

);
 public $timestamps = false;

 public function comments()
{
  return $this->hasMany('App\Comments');
}
  

评论表

class Comments extends Model {

protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'comments';
protected $fillable = array(
    'id',
    'news_id',
    'name',
    'description'
);
 public $timestamps = false;



 public function news()
{
  return $this->belongsTo('App\News','news_id');
}};
  

当我尝试添加此值时,仅创建新闻表    没有相关的评论表。(不会抛出任何异常,只需创建新闻表)

 public function AddData()
{
 $row=new News;
 $row->name="Myname";
 $row->category="vcc";
 $row->type="2";
 $row->comments()->news_id="1";
 $row->comments()->name="someval";

$row->save();
return view::make('first_view');
}

1 个答案:

答案 0 :(得分:0)

插入相关的评论模型时出现问题。有很多方法可以解决您的问题。

解决方案我更喜欢使用:

public function AddData()
{

    // Create news model
    $news = News::create([
        'name' => 'Some name',
        'category' => 'somecategory',
        ....
    ]);

    // Create comment through news model
    // news_id will automatically be inserted
    $comment = $news->comments()->create([
        'name' => 'some name'
    ]);

}

See documentation