I'm trying to retrieve all records from my orders table where an order is associated with a supervisor. Orders and Supervisors are associated with a belongsToMany relationship and have a pivot table.
So my code looks something like this:
$supervisor = User::where('phone_number', $request->msisdn)->first();
$orders = Order::with(['supervisors' => function ($query) {
$query->where('supervisor_id', $supervisor->id);
}])->get();
I'm expecting to get a collection of orders which I'm then passing to a notification but instead get:
[2017-12-12 14:25:27] local.ERROR: Undefined variable: supervisor
{"exception":"[object] (ErrorException(code: 0): Undefined variable: supervisor
Not sure what I'm doing wrong?
You need to use USE to pass $supervisor into the function
$orders = Order::with(['supervisors' => function ($query) use($supervisor) {
$query->where('supervisor_id', $supervisor->id);
}])->get();
For those googling something similar, I used this and it worked:
$supervisor = User::where('phone_number', $request->msisdn)->first();
$orders = Order::whereHas('supervisors', function ($query) use($supervisor) {
$query->where('supervisor_id', $supervisor->id);
})->where('status', '=', 'pending')->get();
Big thanks to p.wright for the help!
Related
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();
i am trying to get object from table orders with related attributes from table order_status_history. From table order_status_history, i need only last record with status 'Reviewing', so i use sort asc by field created_at. My code so far is , but i get error.
$orders = Order::GetOrderHistoryReviewing()->get();
public function scopeGetOrderHistoryReviewing($query)
{
return $query->whereHas('statusHistory', function($q) {
$q->where('status', 'Reviewing')->orderBy('created_at','desc')->first();
});
}
i need one object with relation from second table
this is my error
[2016-07-27 08:37:26] dev.ERROR: exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "orders"
LINE 1: ...ries" where "order_status_histories"."order_id" = "orders"."...
From your question, you're apparently trying to create a scope that returns orders with status, 'Reviewing' and sorts the results in descending order.
You need to remove the first() call from the $q subquery and move orderBy to the end of your $query. Your code should look like.
public function scopeGetOrderHistoryReviewing($query)
{
return $query->whereHas('statusHistory', function($q) {
$q->where('status', 'Reviewing');
})->orderBy('created_at','desc');
}
Then you can do:
$orders = Order::GetOrderHistoryReviewing()->get();
//OR to get the first record
$first_order = Order::GetOrderHistoryReviewing()->first();
I got this query:
$users = DB::table('users')->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('galleries')
->whereRaw('galleries.user_id = users.id');
})->get();
This query selects all users who have gallery. Problem is that I can't use eloquent releationships now. Whenever i try to loop like this:
#foreach ($user->gallery as $gallery)
{{$gallery->name}}
#endforeach
I get error:
Undefined property: stdClass::$gallery
It happens with all other tables. What am I doing wrong here? My realationships are defined and they work just fine, i got problems only in this query. Thanks.
EDIT
Since it's not eloquent query, could you show me example how to write query, into few tables with eloquent. For example, I need all users who have their status approved in example table
First, determine a relationship in the User class, like this:
class User {
// Determine relation to Example table
public function examples() {
return $this->hasMany('Example', 'user_id', 'id'); // second parameter is the foreign key
}
}
Then the query:
User::whereHas('examples', function( $query ) {
$query->where('status','approved');
})->get();
Currently, a criteria BelongsToMany alerts and viceversa. They are related through a pivot table: criteria_id and alert_id.
I am getting all Criteria with the associated Alerts that belongs to the authenticated user, as such:
public function getMatches()
{
$matches = Criteria::whereUserId( Auth::id() )
->has('alerts')
->get();
}
This returns all associated results, whereas now, if a user picks a certain result, I want to be able to show just that. This is what I have so far:
Controller
public function getMatchDetails($alert_id, $criteria_id)
{
$matches = Alert::find($alert_id)
->has('criterias')
->where('criteria_id', $criteria_id)
->get();
}
Which is bringing over the correct variables, however, I am getting a MYSQL error:
Column not found: 1054 Unknown column 'criteria_id' in 'where clause'
select * from `alerts` where `alerts`.`deleted_at` is null and
(select count(*) from `criterias` inner join `alert_criteria` on `criterias`.`id` =
`alert_criteria`.`criteria_id` where `alert_criteria`.`alert_id` = `alerts`.`id`)
>= 1 and `criteria_id` = 7)
Any help would be hugely appreciated.
You could try something like this
public function getMatchDetails($alert_id, $criteria_id)
{
$match = Alert::whereHas('criterias', function ($q) use ($criteria_id) {
$q->where('criteria_id', $criteria_id);
})->find($alert_id);
}
Which will find the alert by id and also check that it has a relationship to criterias meeting those requirements.
I don't know if I understood well the question, but I'm going to try to answer
If you want to pass more than just a variable from the view to the controller, you can do something like this:
View
#foreach($matches as $match)
#foreach($match->alerts as $alert)
<td>{{$alert->pivot->criteria_id}}</td>
<td>{{$alert->id}}</td>
#endforeach
#endforeach
Controller
public function getMatchDetails($id, $var_2 = 0)
{
$myCriteriaIds = Criteria::whereUserId( Auth::id() )
->lists('id');
$match = Alert::find($id)->criterias()
->wherePivot('criteria_id', 'IN', $myCriteriaIds)
->get();
}
Route
Route::post('/users/alert/matches/{id}/{var_2}', array(
'as' => 'users-alert-matches',
'uses' => 'XXXController#getMatchDetails'
));
I have an application with a basic forum system where users can "like" a topic multiple times. My models extend Eloquent and I'm trying to get the sum of votes a user has for a specific topic... Basically, I'm trying to accomplish something like:
$votes = Auth::user()
->votes->has('topic_id', '=', $topic->id)
->sum('votes');
However, when executing this, I get the following error...
Call to a member function sum() on a non-object
I've also tried
public function show($forumSlug, $topicSlug)
{
$topic = Topic::whereSlug($topicSlug)->first();
$votes = Topic::whereHas('votes', function ($q) use ($topic)
{
$q->where('topic_id', '=', $topic->id)->sum('votes');
});
dd($votes);
}
However, with that I receive an error stating:
Unknown column 'ideas.id' in 'where clause' (SQL: select sum(votes)
as aggregate from votes where votes.idea_id = ideas.id and
idea_id = 1)`
You may try something like this (Not sure about your relationship but give it a try):
$topic = User::with(array('topics' => function ($query) use ($topic_id) {
// $query = Topic, so it's: Topic::with('votes')
$query->with('votes')->where('topics.id', $topic_id);
}))->find(Auth::user()->id)->topics->first();
// Count of total votes
dd($topic->votes->count());
P/S: If it doesn't work then please post your model's relationship methods.
I managed to get it working, though I'm not sure I like this approach. I'd love to hear if anyone knows of a better way of doing this...
Basically, I used my relationships to filter() the votes and then used sum() on the filtered collection.
public function show($forumSlug, $topicSlug)
{
$userId = is_null(Auth::user()) ? false : Auth::user()->id;
$topic = Topic::whereSlug($topicSlug)->first();
$votes = $topic->votes->filter(function ($votes) use ($userId)
{
return $votes->user_id == $userId;
})->sum('votes');
return View::make('forums.topics.show', compact('topic', 'votes'));
}