I need to make an insert to 2 related tables in laravel

0

So I have my driver

public function store(Request $request)
    {
        $marca = MarcaAuto::create(['marca' => $request->marca ]);

        ModeloAuto::create([
            'modelo_auto' => $request->modelo,
            'year_model' => $request->year,
            'marca_auto_id' => $marca->id(),
]);

Model MarcaAuto (table1)

class MarcaAuto extends Model
{
   protected $table ='marca_auto';

   protected $fillable = ['marca'];

   public $timestamps = false;

    public function modelo_auto()
   {
         return $this->hasMany(ModeloAuto::class);
   }
}

Model of Auto Model (Table2)

class ModeloAuto extends Model
{
  protected $table ='';

   protected $fillable = [
              'modelo_auto',
              'year_model',
              'marca_auto_id'];

   public $timestamps = false;

   public function modelo_parte_motor()
   {

        return $this->hasMany(ModeloParteMotor::class);
   }

   public function marca_auto()
    {

        return $this->belongsTo(MarcaAuto::class);
    }
}

This is the error that gives me:

  

Call to undefined method Illuminate \ Database \ Query \ Builder :: id ()

    
asked by Christian Cuero 06.05.2018 в 15:08
source

2 answers

0

In the model ModeloAuto you need to specify the name of the table.

protected $table = ' model_auto ';
You can also specify the foreign_key in the belongsTo () relation

class ModeloAuto extends Model
{
  protected $table = 'modelo_auto';

   protected $fillable = [
              'modelo_auto',
              'year_model',
              'marca_auto_id'];

   public $timestamps = false;

   public function modelo_parte_motor()
   {

        return $this->hasMany(ModeloParteMotor::class);
   }

   public function marca_auto()
    {

        return $this->belongsTo(MarcaAuto::class, 'marca_auto_id');
    }
}
    
answered by 06.05.2018 в 15:22
0

first insert in one and use get Last Insert Id to give you the id of the relationship

$ id = DB :: getPdo () -> lastInsertId (); gives you the id that was inserted

    
answered by 22.05.2018 в 19:33