Laravel /ORM 不创建相关 table
Laravel /ORM Doesnt create related table
如何为 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');
}
Comments table
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');
}};
And when I try to add this values it creates only News table
without related Comments table.(Doesn't throw any exception, just creates News table)
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');
}
您插入相关评论模型时出现问题。有很多方法可以解决您的问题。
我更喜欢使用的解决方案:
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'
]);
}
如何为 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');
}
Comments table
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');
}};
And when I try to add this values it creates only News table without related Comments table.(Doesn't throw any exception, just creates News table)
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');
}
您插入相关评论模型时出现问题。有很多方法可以解决您的问题。
我更喜欢使用的解决方案:
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'
]);
}