jeugen
jeugen

Reputation: 342

Using Laravel eloquent relationship (One to Many) returns NULL

when Im using Laravel eloquent - relationships (One To Many) the result is NULL. I have setted up data in "work_hour" table, where "workers_id" has value 2 and there is row in "workers" table with id=2 I followed the documentation "Laravel relationships"

My schema looks like this:

public function up()
    {
        Schema::create('work_hour', function($table){
            $table->increments('id');
            $table->integer('worked_hour');

            $table->time('worked_from');
            $table->time('worked_to');
            $table->integer('workers_id')->unsigned();
            $table->foreign('workers_id')->references('id')->on('workers');
            $table->integer('workday_id');
            $table->integer('offer_id');
        });
    }

PS: columns workday_id, offer_id arent set foreign,yet!

Models are looks like this:

class Worker extends Eloquent{

    protected $fillable = ['first_name', 'last_name'];

}

class Workhour extends Eloquent{

    protected $table    = 'work_hour';

    public function worker(){
        return $this->belongsTo('Worker','workers_id');
    }

}

Controller PS: I searched over the same issue on SO, I tried some opinion, then I commented them out

class WorkerController extends BaseController {
    protected $table    = 'workers';
....
    public function show($id){
        $worker     = Worker::find($id);

    //  $workhour   = Workhour::where('workers_id','=',$worker->id)->get(); 
    // casting the result: works $workhour->toArray()

    //  $workhour   = Worker::find($id)->with('workhour')->get(); 
    //Call to undefined method Illuminate\Database\Query\Builder::workhour()

    //  $workhour   = Worker::with('workhour')->where('id',2)->get(); 
    //Call to undefined method Illuminate\Database\Query\Builder::workhour()

    $workhour   = Worker::find($id)->workhour; 
    // null

        dd($workhour);
        return View::make('worker.show',['worker' => $worker,'workhour'=>$workhour]);
    }

    public function workhour(){
      return $this->hasMany('Workhour','workers_id');
    }


}

Im calling the "show.blade.php" with ".../public/worker/2" (Laravel 4) What am I doing wrong?

Upvotes: 0

Views: 1794

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

You simply need to add the relation to the Model not Controller:

class Worker extends Eloquent{

    protected $fillable = ['first_name', 'last_name'];

    public function workhour(){
      return $this->hasMany('Workhour','workers_id');
    }
}

Upvotes: 1

Related Questions