I have a relationship between employees and items. It's a one-to-many relationship (i.e employee can have many items).
For instance, there are two employees Mark and Bill.
Mark bought items with item_no 1-0234, 1-0235 respectively.
Bill bought items with item_no 1-0236, 1-0237 respectively.
Item numbers are unique and therefore can be used to find the customer who is in possession.
This is my code to find customers items belong to. I select ids of all items using a checkbox.
What I am looking to achieve is, I want to find all employees based on the item selected, retrieve the phone numbers and item_nos using explode and process a message to them.
Controller
<?php
public function processMessage(Request $request)
{
$ids = $request->ids; // i am able to get the item_nos selected, eg. 1 - 0234, 1 - 0236
$split = explode(",", $ids);
if (request()->ajax()) {
$employees = Employee::whereHas('items', function ($emp) use ($split) {
$emp->where('id', $split);
})->get();
$get_name = [];
$get_phone = [];
foreach ($emps as $key => $emps) {
$get_name[] = $emps->name;
$get_phone [] = $emps->phone;
}
}
return ['success' => $get_phone];
}
PS: in the code, imagine i have selected two items with item_nos 1-0234, 1-0236. That is, my code should return two phone numbers, i.e for Mark and Bill but it returns just one of them, which is Mark's. Why is this happening
If i correct, following should help inside your query function-
$emp->whereIn('id',$split);
Related
Using Laravel I have two models, Prize and Tickets, each prize can only have one ticket associated to it.
When iterating over the Prizes, I want to assign a unique ticket to each one. I do this by randomly selecting one from a collection and then removing it from the collection once assigned.
I've noticed at the each of the each call however some of the Prizes have the same Ticket ID, I suspect the already assigned tickets are not being removed from $tickets within the each loop.
Can someone explain why this is and how I can correctly code this?
$prizes = Prize::all()->limit(5)->get();
$tickets = Tickets::all()->limit(5)->get();
// iterate over runner up prizes
$prizes->each(function ($prize, $key) use($tickets) {
// select ticket from bag
$winner = $tickets->random();
// assign to prize
$prize->ticket_winner_id = $winner->id;
// remove id from remainder
$tickets = $tickets->except($winner->id);
});
Why don't you try adding an ampersand before $tickets on the use:
$prizes = Prize::all()->limit(5)->get();
$tickets = Tickets::all()->limit(5)->get();
// iterate over runner up prizes
$prizes->each(function ($prize, $key) use(&$tickets) {
// select ticket from bag
$winner = $tickets->random();
// assign to prize
$prize->ticket_winner_id = $winner->id;
// remove id from remainder
$tickets = $tickets->except($winner->id);
});
That would say to php that you don't want a copy of that variable and you want to mutate it.
I need to make pagination in Laravel, and as I read laravel documentation here is a several way to do it. but in my cases it is a little bit complexity. So let say I've two table in my DB, table1 and table2(many to many relationship), I want to paginate table1 with specific ids. So I mean if table1 contains ids 1,2,3,4,5 ... n, I want to paginate only rows which id is 2 and 3
I have tried :
private function check_wear($type){
$products_id = array(); //here is ids which $type is set as 'ON'
$wears = DB::select("SELECT prod_id FROM wears WHERE ".$type." = 'on' "); //Select specific products ids. (in our case it is **table1**)
foreach ($wears as $wr){
array_push($products_id,$wr->prod_id);
}
return $products_id; //return array with ids which should be paginate
}
public function hat($locale){
$hat_prod_ids = $this->check_wear('coat');
$p=12;
$products = DB::table('products')->paginate($p); // 12 per page
dd($products);
my code only paginate one table with all data, is there any built-in function to somehow write a logic condition? for pagination
If you need to filter your pagination with elements which you've in $hat_prod_ids, you're able to use WhereIn() method, that one checks if your elements (in our case ids) exist in your $hat_prod_ids and returns true or false
$products = DB::table('products')
->whereIn('id',$hat_prod_ids)
->paginate($p);
add that code and now you will be able to paginate only that ids which is matched in your array
I am using Laravel and I have two different collections that contain ID of products
First one is colorProduct and second is tagProduct
so I want to compare these two and get only same ID of products so how can I do this?
$colorProducts = Color::where('code', $request->color)->get()->first()->products;
$tagProducts = $tag->products->where('shop_id', $shop->id);
$colorAndTagProducts = collect();
foreach ($colorProducts->toBase()->merge($tagProducts)->unique('id')->groupBy('id') as $allProducts) {
if ($allProducts->count() >= 1) {
$colorAndTagProducts[] = $allProducts->first();
}
}
here
$colorAndTagProducts
gives me all records form both collection but I only want same record
I dont know, if I understand correctly, but maybe like this?
I suppose Color and Product are in many to many relationship. And Product and Shop/tag in one to many.
$colorId = Color::where('code', $request->color)->get()->first()->id;
$shopId = $shop->id;
$products = Product::whereHas('colors', function ($query) use ($colorId) {
$query->where('id', $colorId); //id or color_id
})->where('shop_id', $shopId)->get();
intersect()
The intersect method removes any values from the original collection
that are not present in the given array or collection. The resulting
collection will preserve the original collection's keys:
I did it with this method
i'm trying to sort a collection, which consists of ids and full names, alphabetically by the last name.
the id comes from a parent class and the full name from the child.
I tried exploding the string and ordering according to the last name, but couldn't really get it to also reorder th IDs properly.
I tried both with sortBy while getting the collection and with usort after retrieving it
$testExaminers=TestExaminer::where('test_id',$request->testid)
->with('examiner')
->get()
->sortBy('examiner.name');
$result = array();
$num=0;
foreach($testExaminers as $testExaminer) {
$result[$num]['id'] = (int) $testExaminer->examiner_id;
$result[$num]['text'] = $testExaminer->examiner->name;
$num++;
}
echo json_encode(['examiners'=>$result]);
The code above works fine for sorting it by first name, but I need it to sort by last name.
user inputs test_id, which gives a list of "TestExaminers", each has a property "examiner_id" associated with a unique "examiner", which in turn has a name "firstname middlename lastname".
so it should look something like this
before sort
$result = [[1,'Alpha Z. Goodman'],[2,'Joe Bman'],[3,'ZZ Top'],[4,'Joe Aman']]
after sort
$result = [[4,'Joe Aman'],[2,'Joe Bman'],[1,'Alpha Z. Goodman'],[3,'ZZ Top']]
Thanks!
How about trying something like this?
$testExaminers = TestExaminer::where('test_id', $request->testid)
->with('examiner')
->get()
->map(function ($item, $key) {
$item->examiner->last_name = array_slice(explode(' ', $item->examiner->name), -1)[0];
return $item;
})
->sortBy('examiner.last_name');
I'm having issues getting a proper count total with my Laravel model.
Model Structure
User
Item
ItemLike
A user can have multiple Items, and each of these Items can have multiple ItemLikes (when a user 'likes' the item).
I can easily get the individual ItemLike counts when using an Item model:
return $this->itemLikes()->count();
But I can't figure out how to get the total # of ItemLike's a User has across all the Item's he owns.
EXAMPLE
User A has 3 Items. Each Item has 5 ItemLike's, for a grand total of 15.
I tried using eager loading on the User model like this:
return $this->items()->with('itemlikes')->get()->count();
But that returns 3 (the # of Items)
These are the queries it ran, which appears like the second query is the one I want, yet every way I try it I still get 3 instead of 15
select * from `items` where `items`.`user_id` = '1000'
select * from `item_likes` where `item_likes`.`item_id` in ('1000', '1001', '1002')
After suggestions from others I found 2 solutions to get the result.
Using whereIn:
$itemViewCount = ItemView::
whereIn('item_views.item_id', $this->items()->lists('id'))
->count();
return $itemViewCount;
2 queries for a total of 410μs
Using join:
$itemViewCount = $this->items()
->join('item_views', 'item_views.item_id', '=', 'items.id')
->count();
return $itemViewCount;
2 queries for a total of 600μs
Isn't it just a case of creating a method that would return the number of items for the model. e.g.:
#UserModel
public function nbLikes()
{
$nbLikes = 0;
foreach($this->items() as $item) {
$nbLikes += $item->itemLikes()->count();
}
return $nbLikes;
}
And then User::nbLikes() should return the piece of data you are looking for?
try this:
$query="select count(il.id) from item_likes il,item itm where il.item_id=itm.id and tm.user_id=1000";