Alex7
Alex7

Reputation: 560

Eloquent doesn't get the "belongsTo" item

I have the Project model and the Contract model. When i execute Project:all() it gets me only the projects without the contract, same for contract. I tried to dd() inside contract and doesn't do anything, like is never executed. I also tried with App\ prefix and without.

use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
    protected $table = 'project';

    public function contract() {
        return $this->belongsTo('Contract');
    }
}

namespace App;
use Illuminate\Database\Eloquent\Model;

class Contract extends Model
{
    protected $table = 'contract';

    public function project() {
         return $this->hasMany('Project', 'ContractID', 'ContractID');
    }
}

I try to retrieve them like this:

$projects = Project::all()->take(10);

Upvotes: 0

Views: 76

Answers (1)

Gravy
Gravy

Reputation: 12465

You have a few problems here.

  1. Project::all()->take(10);

This only returns a collection of projects. You havent specified that you want the contracts also.

$projects = Project::with('contract')->get();
  1. In your belongsTo - You havent specified the column that the table should join on. You need to do this, because you have not used a standard id for primary key and contract_id for foreign key.

  2. unrelated to specific question, but your relationship in contract model is also wrong.

    public function project() { return $this->hasMany('Project', 'ContractID', 'ContractID'); }

If one contract has many projects, then your public function project() should be public function projects();

  1. Finally - Why are you using non-standard table / column naming conventions? What's wrong with contract_id? Are you aware that mysql is non-case sensitive? Also the project table could be renamed projects and the contract table could be renamed contracts. It will make you writing your eloquent relations much easier and makes more sense!

If you used standard naming conventions, then you could just do this to declare your model relations.

namespace App;
use Illuminate\Database\Eloquent\Model;

class Contract extends Model
{
    public function projects() {
         return $this->hasMany('Project');
    }
}

Notice you dont need to specify the table name in the model, or how the table is related to the Project.

Upvotes: 2

Related Questions