Wolrab Wolrab - 3 months ago 24
PHP Question

Eloquent Relationship using DB Laravel

I've got 4 tables.

Clients
Jobs
Rounds
Job_Rounds

I've created the following relationships:

Clients > Jobs
Jobs > Rounds


Here are my models

Client

class Client extends Model
{

protected $dates = [
'created_at',
'updated_at',
'last_done'
];


public function Jobs()
{
return $this->hasMany('App\Job','client_id');
}
}


Job

class Job extends Model
{
protected $dates = [
'created_at',
'updated_at',
'last_done',
'due_date'
];

public function Round()
{
return $this->belongsTo('App\Round','round_id');
}

public function Client()
{
return $this->belongsTo('App\Client','client_id');
}
}


Round

class Round extends Model
{
protected $dates = [
'created_at',
'updated_at',
'date_scheduled',
'date_finished'
];

public function Clients()
{
return $this->hasMany('App\RoundClients', 'round_id');
}

public function Jobs()
{
return $this->belongsToMany('App\Job', 'job_rounds', 'round_id', 'job_id');
}
}


JobRound

class JobRound extends Model
{
public $timestamps = false;
}


On my round view I'm outputting all the jobs not in the round and all the jobs in the round.

I'm doing this by creating a DB::table to perform the check - see my code:

public function show($id)
{
$round = Auth::user()->rounds()->FindOrFail($id);

$not = DB::table('jobs')->whereNotIn('id', function($query) use($round) {
$query->select('job_id')
->from('job_rounds')
->where('round_id', $round->id);
})->get();

$are = DB::table('job_rounds')
->join('jobs', 'job_rounds.job_id', '=', 'jobs.id')
->select('job_rounds.*', 'jobs.*' ,'job_rounds.id as DAS')
->where('job_rounds.round_id',$round->id)
->get();

return view('app.round',compact('round','not','are'));
}


The problem I have is in my view, the Client to Job relationship for outputting the client name won't work as I have created my own DB query, I'm outputting the client information on my view like

Jobs on the round

@foreach($are as $job)
{{ $job->client->first_name }}
@endforeach


Jobs not on the round

@foreach($not as $job)
{{ $job->client->first_name }}
@endforeach


I get the error:


Variable $client not found etc

Answer

Your relationships methods starts with uppercase (which btw, you should change to start with lowercase for standard).

The problem is that your methods and the ones you call are not the same, you need to use the same case in both, like this...

@foreach($are as $job)
    {{ $job->Client->first_name }}
@endforeach

Update

Besides the fact of the case, you are not using Eloquent.
You are just using the database query builder directly.
In order to use Eloquent you must use the Model class static methods, like this:

Job::whereNoIn('id', .....

Instead of this:

DB::table('jobs')->whereNotIn('id', ....