Relationship returning null

Published 6 months ago by martt50

I have two models :

  • Job
  • EstimateDocument

The job model is :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    protected $table = 'vgJcoJob';
    protected $primaryKey = 'Id';

    public function estimateDocument()
    {
        return $this->belongsTo(EstimateDocument::class, 'EstimateDocumentLink');
    }

    // -- SCOPES --
    public function scopeActive($query)
    {
        return $query->where('QuantityOfOpenWorkorder', '!=',0);
    }
}

The EstimateDocument is:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EstimateDocument extends Model
{
    protected $table = 'vgQesEstimateDocument';
    protected $primaryKey = 'DocumentNumber';

    public function jobs()
    {
        return $this->hasMany(Job::class, 'EstimateDocumentLink');
    }

    public function estimates()
    {
        return $this->hasMany(Estimate::class, 'EstimateDocumentLink');
    }
}

I didnt choose the naming of the tables and columns, I had to use those who were already existing.

In one of my controllers, I'm trying to get the associated estimate document from a job, so I do this :

App\Job::find(9)->estimateDocument;

But then it return null.

When I enable the query log, I see this :

array:2 [▼
  0 => array:3 [▼
    "query" => "select top 1 * from [vgJcoJob] where [vgJcoJob].[Id] = ?"
    "bindings" => array:1 [▼
      0 => 9
    ]
    "time" => 25.0
  ]
  1 => array:3 [▼
    "query" => "select top 1 * from [vgQesEstimateDocument] where [vgQesEstimateDocument].[DocumentNumber] = ?"
    "bindings" => array:1 [▼
      0 => "104"
    ]
    "time" => 2.0
  ]
]

I tried to execute the last SQL statement inside of SSMS with the binding value (104) and it returned me something.

What am I doing wrong guys ? Thanks for the help !

Snapey
Snapey
6 months ago (995,105 XP)

If your primary key is not auto incrementing field then you need to use

public $incrementing=false; 

in the model

martt50

It didnt change anything, the relationship is still returning null. By the way I'm not saving anything inside the database, it is only in readonly ...

Snapey
Snapey
6 months ago (995,105 XP)

you put that in the Estimatedocument model?

martt50

I did !

Please sign in or create an account to participate in this conversation.