Kamran G. Kamran G. - 6 months ago 15
PHP Question

Laravel /ORM Doesnt create related table

How can i add value to a ORM related variable

Its contain a news and comments Model

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 am trying to add this values its create only News table
without related Comments table.(Doesnt throw any exeption ,just create 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');
}

Answer

There is a problem when you are inserting your related Comment model. There are many ways to solve your problem.

Solution I prefer to use:

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

Comments