How to apply distinct in payment_user_history.sid - laravel

Here is my results in postman
and i want to show only one sid even if have 2 in results
'''
"results": [
{
"sid": 2,
"id": 2,
"user_id": "S01202100002",
"name": "FRANK AMPLE WALKER",
"LRN": null,
"grade_level": 1
},
{
"sid": 2,
"id": 4,
"user_id": "S01202100002",
"name": "FRANK AMPLE WALKER",
"LRN": null,
"grade_level": 1
},
{
"sid": 3,
"id": 3,
"user_id": "S01202100003",
"name": "NEIL DEST MORGAN",
"LRN": null,
"grade_level": 2
}
]
}
here is my code
public function billingpaymentaccount(){
$fetch = DB::table('payment_user_history')
->leftJoin('tbl_accounts', 'payment_user_history.sid', '=', 'tbl_accounts.id')
->leftJoin('tbl_enrollment', 'payment_user_history.sid', '=', 'tbl_enrollment.student_id')
->select('payment_user_history.sid','payment_user_history.id', 'tbl_accounts.user_id',
DB::raw('concat(tbl_accounts.first_name, " ", tbl_accounts.middle_name, " ",
tbl_accounts.last_name) as name'), 'tbl_accounts.LRN', 'tbl_enrollment.grade_level')
->where('tbl_accounts.account_types',10)
->get();
return response()->json(['results' => $fetch], 200);
}

You can use the ->distinct() modifier to return unique rows. However, payment_user_history.id needs to be removed from your select statement for the query to only return one row per sid.
// note the added distinct
$fetch = DB::table('payment_user_history')->distinct()
->leftJoin('tbl_accounts', 'payment_user_history.sid', '=', 'tbl_accounts.id')
->leftJoin('tbl_enrollment', 'payment_user_history.sid', '=', 'tbl_enrollment.student_id')
// note the removed payment_user_history.id
->select('payment_user_history.sid', 'tbl_accounts.user_id', DB::raw('concat(tbl_accounts.first_name, " ", tbl_accounts.middle_name, " ", tbl_accounts.last_name) as name'), 'tbl_accounts.LRN', 'tbl_enrollment.grade_level')
->where('tbl_accounts.account_types',10)
->get();
If you need to keep the payment_user_history.id field, then you have to decide how to aggregate it to one row (e.g., using the max or min and a group by clause).

Related

Filter Data with Pivot Table Laravel Eloquent

I want to filter users based on their subscription_status which s stored in a pivot table.
I have Three tables users , subscription_packages , subscription_package_user
$user=User::with(['studentDetails','subscriptionsSatus.courses'])
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
this code return the response is
[
{
"id": 44,
"first_name": "Abcd Test",
"last_name": "Test lastname",
"student_details": null,
"subscriptions_satus": [
{
"id": 1,
"name": "Gold",
"price": 3000,
"user_id": "2"
"pivot": {
"user_id": 44,
"subscription_package_id": 1,
"subscription_status": "on_free_trial",
"expires_on": null,
"id": 9
},
"courses": [
{
"id": 18,
"title": "English Grammar for Class 3",
"price": 400,
"strikethrough_price": null,
"status": "draft",
"user_id": 2,
"image": "http://127.0.0.1:8000/courses/1615702915.png",
"description": null,
"pivot": {
"subscription_package_id": 1,
"course_id": 18,
}
}
]
}
]
}]
i want to return only users who having subscription_status =$filter.
$filter='acive'or 'on_free_trail'
my model is
public function subscriptionsSatus()
{
return $this->belongsToMany(SubscriptionPackage::class)->withTimestamps()->withPivot('subscription_status','expires_on','id');
}
I havetried
$filter=$request->input('filter')??"active";
$user=User::with(['studentDetails','subscriptionsStatus.courses'])
->whereHas('subscriptionsStatus', function($query) use($filter){
$query->wherePivot('subscription_status','=',$filter);
})
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
But Got error Column not found 'pivot'
You need to use wherePivot along with the orWhere like below:
public function subscriptionsStatus()
{
return $this->belongsToMany(SubscriptionPackage::class)
->withTimestamps()
->withPivot('subscription_status','expires_on','id')
->wherePivot(function($q){
return $q->where('subscription_status','=','active')
->orWhere('subscription_status','=','on_free_trail');
});
}
Update
Or in your controller:
$user=User::with(['studentDetails','subscriptionsStatus.courses'])
->whereHas('subscriptionsStatus', function($query) use($filter){
$query->withPivot('subscription_status')
->wherePivot('subscription_status','=',$filter);
})
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();

Laravel Query Builder does not run query correctly even thought it binds correctly

I have a problem with the Laravel Query Builder. When I try to bind a variable, which would include some sort of sql code, into my binding parameter, it returns no results. If I run enableQueryLog() I can see that the query and the binding is correct. So the code provides a perfectly fine query but yet it does not perform accordingly.
I've already tried printing out all the variables that matter. I enabled a query log to see if everything is set correctly, which it is. When I put in the variable in my whereRaw() just as it is without binding, it works fine. Just not with the binding.
This is the code I run:
public function getCarbrands() {
$name = 'name != Ford';
try {
$brands = DB::table('ni_carbrands')
->whereRaw(':name',['name'=>$name])
->select('id','name')
->get();
echo json_encode( array('info' => 1 ,'status' => 'Successfully found car brands', 'details' => $brands));
} catch(Exception $e){
echo json_encode( array('info' => 0 ,'status' => 'Error finding car brands', 'e' => $e));
}
}
I know that this use of the binding feature is unnecessary, it is merely a test for some other functions I wanna build.
This is what my Query Log returns:
array:1 [▼
0 => array:3 [▼
"query" => "select `id`, `name` from `ni_carbrands` where :name"
"bindings" => array:1 [▼
0 => "name != Ford"
]
"time" => 190.25
]
]
The components of the query all seem correct, but yet it seems to have some trouble producing it.
The expected results would be something like this:
{
"info": 1,
"status": "Successfully found car brands",
"details": [
{
"id": 1,
"name": "Toyota"
},
{
"id": 2,
"name": "Fiat"
},
{
"id": 3,
"name": "Iveco"
},
{
"id": 4,
"name": "Citroën"
},
{
"id": 5,
"name": "Opel"
},
{
"id": 6,
"name": "Mercedes"
},
{
"id": 8,
"name": "Volkswagen"
},
{
"id": 9,
"name": "Renault"
},
{
"id": 10,
"name": "MAN"
},
{
"id": 11,
"name": "Nissan"
},
{
"id": 12,
"name": "Hyundai"
},
{
"id": 13,
"name": "Peugeot"
}
]
}
But the actual result is:
{"info":1,"status":"Successfully found car brands","details":[]}
I'd greatly appreciate some help.
It seems like you cant bind a string containing an operator.
Have a look into this one Can I bind a parameter to a PDO statement as a comparison operator?
And this one binding not null in pdo
Bad raw condition:
whereRaw(':name',['name'=>$name])
Just like this:
$brands = DB::table('ni_carbrands')
->select('id','name')
->whereRaw($name)
->get();
you can this use this kind of also
$brands = DB::table('ni_carbrands')
->select('id','name')
->where('name', '!=', 'Ford')
->get();
otherwise you can set where condition in dynamic field
like
->where($name, '!=', 'Ford')
$name = 'name != Ford';
$brands = DB::table('ni_carbrands')
->whereRaw(':name',['name'=>$name])
->select('id','name')
->get();
this is equivalent query
select from ni_carbrands where 'name != Ford'
of course it doesn't work, because you have so
select from ni_carbrands where name != Ford
problem in quotes

Laravel : Using WITH and left join filter table data

On my query join 4 tables. I got all response but the three table which has a same field name 'title' and it is mismatch. So how can i solve this.Is there any way to filter filed which i want before leftjoin or after leftjoin query.
My query look like :
$userPost = Post::with(['product','postattributes' => function ($query) {
$query ->leftjoin('attributes', 'attributes.id', '=', 'post_attributes.attribute_id')
->leftjoin('categories', 'categories.id' , '=', 'attributes.category_id');
}])->whereUserId($user->id)->whereStatus("Active")
->get();
And response i gt :
"postattributes": [
{
"id": 1,
"attribute_id": 1,
"post_id": 136,
"created_at": "2018-04-27 18:46:28",
"updated_at": "2018-04-27 18:46:28",
"product_id": 1,
"category_id": 1,
"parent_id": null,
"title": "Shape",
"status": "Active",
"sort_order": 1
},
{
"id": 1,
"attribute_id": 2,
"post_id": 136,
"created_at": "2018-04-27 18:46:28",
"updated_at": "2018-04-27 18:46:28",
"product_id": 1,
"category_id": 1,
"parent_id": null,
"title": "Shape",
"status": "Active",
"sort_order": 1
}
]
Now i want to use title as category_title on categories table.
how can i do this ?
You can use select for this:
$userPost = Post::with(['product','postattributes' => function ($query) {
$query->select('categories.id', 'attribute_id','post_id', 'created_at', 'updated_at','product_id','category_id', 'parent_id', 'categoris.title as category_title', 'status', 'sort_order')
->leftjoin('attributes', 'attributes.id', '=', 'post_attributes.attribute_id')
->leftjoin('categories', 'categories.id' , '=', 'attributes.category_id');
}])->whereUserId($user->id)->whereStatus("Active")
->get();
In select you can set all fields that you need, in this example I added all from your list.

Related $query->with but "pick properties as"

I am using Laravel 5.5.13.
I am trying to fetch all Extensions but with certain extra properties based on their relations.
My goal is to get data like this, I am trying to get the latest_comment_date, thumbs_count, and thumbs_yes_count:
[
{
"id": 3,
"name": "Pull Refresh",
"created_at": "2017-11-10 06:04:44",
"updated_at": "2017-11-10 06:04:44",
"latest_comment_date": "2017-11-10 05:46:25",
"thumbs_count": 10,
"thumbs_yes_count": 2
}
]
I tried this:
return Extension::with([
'comments' => function($query) { // rename to 'latest_comment_date'
$query->orderBy('created_at', 'desc')->take(1);
},
'thumbs' => function($query) { // rename to 'thumbs_count'
$query->count();
},
'thumbs' => function($query) { // rename to 'thumbs_yes_count'
$query->where('like', '=', true)->count();
}
])->get();
This gives me data like this:
[
{
"id": 3,
"name": "Pull Refresh",
"created_at": "2017-11-10 06:04:44",
"updated_at": "2017-11-10 06:04:44",
"comments": [
{
"id": 10,
"body": "heck ya baby",
"displayname_id": 2,
"extension_id": 3,
"created_at": "2017-11-10 18:31:31",
"updated_at": "2017-11-10 18:31:31"
}
],
"thumbs": []
}
]
May you please help me to "pick as" stuff as I showed at top most?
For counting you should use withCount like so:
return Extension::withCount(
'thumbs',
'thumbs as thumbs_yes_count' => function($query) {
$query->where('like', '=', true);
})->get();
Reference: Counting related models
And for taking latest comment, you should create extra relationship like so:
public function latestComment()
{
return $this->hasOne(Comment::class)->orderBy('created_at', 'desc');
}
so the whole code would look like this:
return Extension::with('latestComment')->withCount(
'thumbs',
'thumbs as thumbs_yes_count' => function($query) {
$query->where('like', '=', true);
})->get();

Laravel - way to sum total_balance of all children.balance columns with just one request?

I need to simplify my data structuring. I want to get sum of balances in children accounts of a parent account. Here is how my object is structured:
Account Types
Children Types
Account 1 ( has balance of 9000 )
Account 2 ( has balance of 5000 )
I want to get total balance of all children accounts:
Account Types
Children Types - total_balance = 14000
How to do this without looping through the object, but using only the query builder of Laravel?
This is the request in my controller:
$user = \Auth::user()->id;
$accounts = AccountType::where('parent_id', 0)
->where('virtual', '=', 0)
->with(['children', 'children.accounts' => function ($query) use ($user) {
$query->where('user_id', '=', $user);
}])
->get();
return $accounts;
And this is the object that I get:
{
"id": 1,
"name": "Savings",
"parent_id": 0,
"virtual": 0,
"created_at": "2016-10-27 10:28:59",
"updated_at": "2016-10-27 10:28:59",
"children": [
{
"id": 2,
"name": "General Savings",
"parent_id": 1,
"virtual": 0,
"created_at": "2016-10-27 10:28:59",
"updated_at": "2016-10-27 10:28:59",
"accounts": [
{
"id": 25,
"institution_id": 0,
"balance": 9000,
"account_nickname": "Money Laundering",
"is_primary": 1,
"account_type_id": 2,
"user_id": 2,
"created_at": "2016-10-31 16:47:23",
"updated_at": "2016-10-31 16:47:23"
},
{
"id": 26,
"institution_id": 0,
"balance": 5000,
"account_nickname": "Moneymarket Savings",
"is_primary": 0,
"account_type_id": 2,
"user_id": 2,
"created_at": "2016-10-31 16:48:30",
"updated_at": "2016-10-31 16:48:30"
}
]
}
]
Is there a way to do that?
This should give you a list of all account types a user has containing a the total_balance of all accounts under each account_type:
$userAccountTypes = DB::table('account_types AS at')
->select(DB::Raw('*, SUM(a.balance) AS total_balance'))
->join('account_types AS ct', 'ct.parent_id', '=', 'at.id')
->join('accounts AS a', 'a.account_type_id', '=', 'ct.id')
->where('at.parent_id', 0)
->where('a.user_id', $user)
->groupBy('ct.id')
->get();

Resources