mercredi 2 août 2017

Laravel Repository Pattern - belongsTo not inserting

I have the following Models:

  • Employees

  • Addresses

The models for each:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
      protected $table = 'employees';


      public function address() {
          return $this->belongsTo('App\Address'); 
      }
}

I have the following Repository for Employees

namespace App\Repositories\Employees;

interface EmployeeInterface
{
    public function all($columns = array('*'));

    public function paginate($perPage = 15, $columns = array('*'));

    public function create(array $data);

    public function update($id, array $data);

    public function delete($id);

    public function find($id, $columns = array('*'));

    public function findBy($attribute, $value, $columns = array('*'));

    public function findByLike($attribute, $value, $columns = array('*'));

    public function address(); 

}

There is a column address inside the Employees table which links the address to the addresses table.

I'm inserting through the following way inside my controller:

class EmployeesController extends Controller {

private $employee;

public function __construct(EloquentEmployee $employee)
{
     $this->employee = $employee;
}

public function store(Request $request) 
{
     $this->employee->address()->firstOrCreate(['postcode' => 'BLAH']); 
     $this->employee->create(['first_name' => 'Stackoverflow']); 
}

The issue is that, the address is getting created and also the Employee. But the address is not being linked inside the Employees table and just shows as null. Is there a way to get them to link through using the repository pattern?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire