Laravel hasMany to Belongs to returns undefined - php

I know this has been asked before but specific to my case I could't find an answer that worked.
Currently I have two models.
App\JobStatus
App\Customer
In model App\JobStatus I have this:
public function customer()
{
return $this->belongsTo('App\Customer');
}
In model App\Customer I have this:
public function jobs()
{
return $this->hasMany('App\JobStatus', 'customer_id');
}
'customer_id' is the foreign key. I then try to access customer from Jobstatus in my controller like so:
$testMePlease = JobStatus::first()->where('qb', '=', 1);
$testMePlease->customer;
I have attempted to dd this. To put it in foreach loop. I've also tried $testMePlease->customer->customer_name. Customer_name being a column in the table and I get back the same error: "Undefined property: Illuminate\Database\Eloquent\Builder::$customer"
Any ideas what I'm doing wrong?

Try to change
$testMePlease = JobStatus::first()->where('qb', '=', 1);
To
$testMePlease = JobStatus::where('qb', '=', 1)->first();

Related

Getting count of nested relationship with 'withCount' method

I'm in need of help of figuring out how to get withCount() to work with nested relationships.
I have so far tried this
return CharityArea::with('campaigns.sponsor', 'campaigns.charityArea', 'campaigns.charityDetail')->withCount('campaigns.users')->where($matchTheseThings)->get();
Basically, I want to get the count of the users in the campaigns model.
The relationship on the CampaignsModel looks like this:
public function users(){
return $this->hasMany('App\UserPreferences', 'campaign_id', 'id');
}
The relationship to campaigns in CharityArea looks like this
public function campaigns(){
return $this->hasMany('App\Campaigns', 'charity_area_id', 'id');
}
Laravel throws and error saying that 'campaigns.users' is not found.
Any ideas on how else to do this?
Thanks.
You can use first set a ManyThrough relation in your CharityArea model.
function users()
{
return $this->hasManyThrough('App\UserPreferences', 'App\Campaigns');
}
Then you can call withCount() on it:
return CharityArea::with('campaigns.sponsor', 'campaigns.charityArea', 'campaigns.charityDetail')
->withCount('users')
->where($matchTheseThings)
->get();

Get other table column value in laravel 5.4

Hello i have below query
Deal::with(array('deal_category'=>function($query){
$query->select('name as dealcategory');
}))->get()
when i try to retrieve dealcategory it does not return any value. I have defined relationship in model like
Deal Model
public function deal_category()
{
return $this->belongsTo('App\DealCategory', 'deal_category_id', 'id');
}
And Deal category model like
public function deals(){
return $this->hasMany('App\Deal','deal_category_id');
}
can anyone help how can i get categoryname?
You have to select the primary key to retrieve the necessary results.
Deal::with(array('deal_category'=>function($query){
$query->select('id', 'name as dealcategory');
}))->get()
Use facade DB.
You can try something like this:
DB::table('deal as d')
->join('deal_category as dc', 'd.id', '=', 'dc.deal_id')
->select('d.name as dealname', 'dc.categoryname')
->get();

Laravel Eloquent Eager loading confusion

In Laravel I have a model that looks like this:
class Recipient extends Model
{
public $table = 'recipients';
public function location()
{
return $this->belongsTo('App\Location');
}
public function teams()
{
return $this->belongsToMany('App\Team');
}
public function company()
{
return $this->belongsTo('App\Company');
}
}
To query that model I do this:
$recipients = Recipient::with('location')
->with('teams')
->where('company_id',Auth::user()->company_id)
->where('teams.id', 10)
->get();
On doing so, I get an error saying that laravel can't find teams.id, as it is only querying the parent recipient table. Wondering what I'm doing wrong, I thought the with method was to eager load / inner join records? Do I need to use a DB: inner join instead? Or am I missing something?
Use the whereHas method for this:
Recipient::with('location')
->where('company_id', auth()->user()->company_id)
->whereHas('teams', function($q){
return $q->where('id', 10);
})
->get();
try being explicit and add a select statement. Sometimes a relationship does not show up when not selected. Include the IDs else it won't work

Laravel: return JSON model with relation

I'm trying to query a model with a relation.
My method:
public function getLabel($layerId)
{
$labelGroups = Forum_label_group::
join('forum_layer_to_labels', function ($join) use ($layerId) {
$join->on('forum_layer_to_labels.layerId', '=', 'forum_label_groups.id');
})->with('labels')->get()->toJson();
return $labelGroups;
}
The output:
[{"id":4,"name":"Demogruppe","description":"bla","required":1,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labelGroupId":2,"layerId":2,"labels":[]},{"id":5,"name":"Demogruppe 2","description":"bla 2","required":0,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labelGroupId":2,"layerId":3,"labels":[]}]
As you can see, the label relation is empty.
Now I'm trying to query a single model instead off all:
public function getLabel($layerId)
{
return Forum_label_group::with('labels')->first()->toJson();
}
the new output:
"{"id":2,"name":"Demogruppe","description":"bla","required":1,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labels":[{"id":5,"title":"Demo rot","name":"demo-rot","typeId":3,"groupId":2,"created_at":"2016-10-22 12:29:47","updated_at":"2016-10-22 12:29:47"},{"id":6,"title":"Demoblau","name":"demoblau","typeId":1,"groupId":2,"created_at":"2016-10-22 12:30:03","updated_at":"2016-10-22 12:30:03"}]}"
And as you can see now, everything is fine. The whole relation exists. Is there a problem with the initial query? The relation seems to be ok.
And of course it was an small issue ;)
I forgot to add a select() on my query. The original id has been overwritten by the join(). So the method tried to query an labelGroup that doesn't exist.
The correct query:
public function getLabel($layerId)
{
$labelGroups = Forum_label_group::
join('forum_layer_to_labels', function ($join) use ($layerId) {
$join->on('forum_layer_to_labels.layerId', '=', 'forum_label_groups.id');
})->select('forum_label_groups.*')->with('labels')
->get();
return $labelGroups;
}

Laravel Multiple Models Eloquent Relationships Setup?

I have 3 models
User
Pick
Schedule
I'm trying to do something like the following
$picksWhereGameStarted = User::find($user->id)
->picks()
->where('week', $currentWeek)
->first()
->schedule()
->where('gameTime', '<', Carbon::now())
->get();
This code only returns one array inside a collection. I want it to return more than 1 array if there is more than 1 result.
Can I substitute ->first() with something else that will allow me to to return more than 1 results.
If not how can I set up my models relationship to allow this to work.
My models are currently set up as follow.
User model
public function picks()
{
return $this->hasMany('App\Pick');
}
Schedule model
public function picks()
{
return $this->hasMany('App\Pick');
}
Pick model
public function user()
{
return $this->belongsTo('App\User');
}
public function schedule()
{
return $this->belongsTo('App\Schedule');
}
Since you already have a User model (you used it inside you find method as $user->id), you can just load its Pick relationship and load those Picks' Schedule as follows:
EDIT:
Assuming you have a schedules table and your picks table has a schedule_id column. Try this.
$user->load(['picks' => function ($q) use ($currentWeek) {
$q->join('schedules', 'picks.schedule_id', '=', 'schedules.id')
->where('schedules.gameTime', '<', Carbon::now()) // or Carbon::now()->format('Y-m-d'). See what works.
->where('picks.week', $currentWeek);
}])->load('picks.schedule');
EDIT: The code above should return the user's picks which have a schedules.gameTime < Carbon::now()
Try it and do a dump of the $user object to see the loaded relationships. That's the Eloquent way you want.
Tip: you may want to do $user->toArray() before you dump $user to see the data better.
EDIT:
The loaded picks will be in a form of Collections so you'll have to access it using a loop. Try the following:
foreach ($user->picks as $pick) {
echo $pick->schedule->gameTime;
}
If you only want the first pick from the user you can do: $user->picks->first()->schedule->gameTime
I think a foreach loop may be what you're looking for:
$picks = User::find($user->id)->picks()->where('week', $currentWeek);
foreach ($picks as $pick){
$pickWhereGameStarted = $pick->schedule()->where('gameTime', '<', Carbon::now())->get();
}
Try this and see if it's working for you

Categories