I'm new in Laravel and I'm trying to merge or join to arrays in one array, which have a one-to-many relationship.
These are the models:
class GroupMenu extends Model
{
public function optionmenu()
{
return $this->hasMany(OptionMenu::class, 'groupmenu_id');
}
}
class OptionMenu extends Model
{
public function groupmenu()
{
return $this->belongsTo(GroupMenu::class, 'groupmenu_id');
}
}
Also I have this function which returns the following arrangement.
public function getOptionMenus()
{
$optionmenu = OptionMenu::whereHas('tipousuario', function ($query) {
$query->where('tipousuario_id', session()->get('tipousuario_id'))->orderBy('orden');
})->get()->toArray();
return $optionmenu;
}
The output is like that:
array:17 [▼
0 => array:2 [▼
"id" => 1
"groupmenu_id" => 1
]
1 => array:2 [▼
"id" => 2
"groupmenu_id" => 1
]
2 => array:2 [▼
"id" => 3
"groupmenu_id" => 1
]
3 => array:2 [▼
"id" => 4
"groupmenu_id" => 2
]
4 => array:2 [▼
"id" => 5
"groupmenu_id" => 2
]
My problem is that I want to have an array where for each groupmenu has within it the array of the optionmenu, something like that:
0 => array:2 [▼
"id" => 1
"optionmenu" => array:3[array of all the optionsmenu that belongs to the groupmenu]
]
1 => array:2 [▼
"id" => 2
"optionmenu" => array:1[array of all the optionsmenu that belongs to the groupmenu]
]
If you want to get all GroupMenu records with related OptionMenu records without any constraint
$data = GroupMenu::with('optionmenu')->get();
However if you want to constrain the related OptionMenu records for each GroupMenu parent record based on the id of tipousuario - which you get from session as shown in your question then you can try something like
$data = GroupMenu::with([
'optionmenu' => fn($query) =>
$query->whereHas('tipousuario', fn($q) =>
$q->where('tipousuario_id', session()->get('tipousuario_id'))->orderBy('orden')
)
])->get();
Related
My aim here is to remove the whole object from the array if "record_type" is null. I should then only be left with data that has a record_type set in the array.
I've looked into the array filter not sure how I target the data within the array "record_type". My only other thought is to import to a database and then SQL query what I want then delete data I've had which is much more overkill.
<pre>
array:36 [▼
0 => array:3 [▼
"type" => "comment"
"line_index" => 0
"text_b64" => "OyBjUGFuZWwgZmlyc3Q6ODguMC4xMiAodXBkYXRlX3RpbWUpOjE2MTg1NDYxNDIgQ3BhbmVsOjpab25lRmlsZTo6VkVSU0lPTjoxLjMgaG9zdG5hbWU6cjExOC5sb24yLm15c2VjdXJlY2xvdWRob3N0LmNvbSBs ▶"
]
1 => array:3 [▼
"line_index" => 1
"text_b64" => "OyBab25lIGZpbGUgZm9yIG9ha3RyZWVkZW50YWxtb3J0aW1lci5jby51aw=="
"type" => "comment"
]
2 => array:3 [▼
"text_b64" => "JFRUTCAxNDQwMA=="
"line_index" => 2
"type" => "control"
]
3 => array:6 [▼
"line_index" => 3
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"record_type" => "SOA"
"ttl" => 30
"type" => "record"
"data_b64" => array:7 [▶]
]
4 => array:6 [▼
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 10
"record_type" => "NS"
"ttl" => 30
"type" => "record"
"data_b64" => array:1 [▶]
]
5 => array:6 [▼
"ttl" => 30
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 11
"record_type" => "NS"
"data_b64" => array:1 [▶]
"type" => "record"
]
</pre>
Goal: only be left with data that has a 'record_type' set (not null) in the array
Solution: use array_filter() on your source array ($arr) and filter for records with 'record_type' != "NS" (assuming "NS" is what you refer to as null, or not set).
<?php
$result = array_filter(
$arr,
function (array $record) {
if (isset($record['record_type'])) {
return $record['record_type'] != "NS";
} return null;
}
);
working demo
EDIT
If you want to filter for only those records that are of a certain type, e.g. type 'record', following should help:
<?php
$result = array_filter(
$arr,
function (array $record) {
if ($record['type'] == 'record') {
return true;
} return false;
}
);
working demo
If your Goal is to filter array to remove any inner-array that hasn't a record_type, So use array_filter with a callback function fn to check that record_type exist with isset function.
array_filter($arr, fn($el)=>isset($el["record_type"]));
I have pivot table vacancy_tag. I tried different options (value,select, lists and etc), but didn't go further than that. My request:
Vacancy::where('id',1)->with(['tags' => function ($q){
$q->select('tags.id')->pluck('id');
}])->get()->toArray();
return this:
"id" => 1,
"title" => "pm",
"tags" => array:2 [▼
0 => array:1 [▼
"id" => 1
]
1 => array:1 [▼
"id" => 2
]
but need this:
"id" => 1,
"title" => "pm",
"tags" => [
1,
2
]
I would like to receive the data result in a query, without using a methods transformation of the collection, if possible.
PS: I slightly corrected the example, need to display all fields of the vacancy + an array of tags.
I have a problem to passing array of arrays from controller to view in Laravel. I've done some research but none of topics helped. My tables are Shops, Items, Items Price. Shops contains shop id, which I get for use from url application/id. In Items Price I got information like shop_id , item_id (these two are FK), price. This table shows which items are in which shops. And in Items I have information about items: id ,picture. When I go to application/1, I want site to show items, which are in this specific shop, information.
My controller method:
public function getItems($id)
{
$items=ItemPrice::where('shop_id', $id)->select('item_id')->get()->toArray();
foreach($items as $item)
$products[] = array(Item::where('id',$item)->get()->toArray());
$shops=Shop::all();
return view('shop')->with(compact(['products','shops']));
}
when I debugging array with dd($products); I get:
array:4 [▼
0 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 1
"name" => "Item1"
"price" => 0.8
"type" => 2
"img_dir" => "svg/d.jpg"
]
]
]
1 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 2
"name" => "Item2"
"price" => 1.1
"type" => 2
"img_dir" => "svg/d2.jpg"
]
]
]
2 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 3
"name" => "Item3"
"price" => 3.1
"type" => 5
"img_dir" => "svg/p1.jpg"
]
]
]
3 => array:1 [▼
0 => array:1 [▼
0 => array:5 [▼
"id" => 4
"name" => "Item4"
"price" => 1.56
"type" => 5
"img_dir" => "svg/p2.jpg"
]
]
]
]
In view I do foreach #foreach($products as $product) and I get error:
Trying to get property 'img_dir' of non-object.
Any help would be appreciated.
Try like this
public function getItems($id)
{
$items = ItemPrice::where('shop_id', $id)
->select('item_id')
->pluck('item_id')
->toArray();
$products = Item::whereIn('id', $items)->get();
$shops = Shop::all();
return view('shop', compact('products','shops'));
}
You have some nested arrays in $products. What you think is a product is in fact an array. Maybe if you simplify your $products variable content :
public function getItems($id) {
$items = ItemPrice::where('shop_id', $id)->select('item_id')->get()->toArray();
$products = [];
foreach($items as $item) {
$products[] = Item::where('id',$item)->get();
}
$shops = Shop::all();
return view('shop')->with(compact(['products', 'shops']));
}
Look at this line
$products[] = array(Item::where('id',$item)->get()->toArray());
$products is an array, and you assign a new element which is an array made by the array value of your query (which contains array).
So you have a 3-level nested array which leads to confusion.
Why don't you just send to your blade view $products = Item::where('id',$item)->get(); ?
I want to have an array with the info about each registration type associated with a registration. For example if for the registration with id "1" the user selected two registration types of type "General" and one of the type "Plus" the $regTypes array should have this content with 2 item:
'registrationTypes' => [
[
'name' => 'general',
'price' => '5',
'quantity' => '2'
],
[
'name' => 'plus',
'price' => '10',
'quantity' => '1'
]
]
The registration_types table have the name and the price. So I have this query to get some info about a registration in a conference.
$registration = Registration
::with('conference', 'Conference.registrationTypes')->where('id', 1)->first();
And then I have this code to create the array with the necessary info:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$regTypes [
'regType' => [
'name' => $registration->conference->registrationTypes[$key]['name'],
'price' => $registration->conference->registrationTypes[$key]['price']
]
];
}
My doubt is how to also store the quantity in the $regTypes array. Because the quantity is not stored in the database.
Maybe to get the quantity is necessary to do antoher query. With this code below:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
//dd($registrationTypeDetails);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dump($type_counts);
The $type_counts shows the quantity of each registration type associated with the registration:
array:2 [▼
"general" => 2
"plus" => 1
]
Do you know how to use this $type_counts content to store the quantity properly in the $regTypes array?
To directly answer your question (IE not change the controller code, just "use this $type_counts content to store the quantity properly in the $regTypes array"), I'm hopeful this should work for you:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$typeName = $registration->conference->registrationTypes[$key]['name'];
$regTypes [
'regType' => [
'name' => $typeName,
'price' => $registration->conference->registrationTypes[$key]['price'],
'quantity' => $type_counts[$typeName]
]
];
}
Basically just pulling the count from the $type_counts array based on the name of the Registration Type being the key that you added in the foreach ($registrationTypeDetails->participants as $p) loop.
Depending upon what you are after, it might be easier just to loop on the registration types, rather than go through $registration->conference->registrationTypes. This way you don't have duplicates. But that assumes you don't want duplicates :)
I hope this code useful for you .If you need the number of participants in any type, you can use the following code:
$registration = Registration::with('conference','Conference.registrationTypes','Conference.registrationTypes.participants')
->where('id',$regID)->first();
$result=$registration->conference->registrationTypes->each(function ($item, $key) use($registration) {
$item['try_count']=$item->participants->count();
});
dd($result->toArray());
I added the try_count variable to the final result:
array:2 [▼
0 => array:6 [▼
"id" => 1
"name" => "general"
"price" => 0
"conference_id" => 1
"try_count" => 8
"participants" => array:8 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
6 => array:5 [▶]
7 => array:5 [▶]
]
]
1 => array:6 [▼
"id" => 2
"name" => "plus"
"price" => 1
"conference_id" => 1
"try_count" => 5
"participants" => array:5 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
]
]
]
I'm currently using jenseggers-mongodb eloquent in laravel 5 with mongodb 3.0.3.
I'm trying to join two different tables as follows:
User Model
public function userpayment() {
return $this->hasMany('App\Models\Userpayment', 'user_id', '_id');
}
Userpayment model
public function user() {
return $this->belongsTo('App\Models\User','user_id');
}
I'm using repository pattern
public function __construct() {
$this->model = new User;
}
return $this->model->with(array('userpayment'=>function($query){
$query
->groupBy('dealCodeNumber')
->get();
}))
->where('_id',$sid)
->get();
groupBy dealCodeNumber returns NULL.
array:1 [▼
0 => array:15 [▼
"_id" => "55813f4cbc59a3f1372e9e6f"
"full_name" => "Varathan"
"username" => "shopsyadmin"
"web_url" => ""
"userpayment" => []
]
without groupby returns all.
array:1 [▼
0 => array:15 [▼
"_id" => "55813f4cbc59a3f1372e9e6f"
"full_name" => "Varathan"
"username" => "shopsyadmin"
"userpayment" => array:2 [▼
0 => array:57 [▼
"_id" => "55816ce7cc7d4bac0d000029"
"dealCodeNumber" => "1398410837"
"inserttime" => "1398411401"
"status" => "Pending"
]
1 => array:57 [▶]
]
Querylog with groupby
[query] => shopsy_user_payment.aggregate([{"$match":{"user_id":{"$in":["55813f4cbc59a3f1372e9e6f"]}}},{"$group":{"_id":{"dealCodeNumber":"$dealCodeNumber"}
Why groupby returns null?
To group an column it must be selected before grouping. Changing code to below works:
return $this->model->with(array('userpayment'=>function($query){
$query
->select('product_id','user_id','dealCodeNumber')
->groupBy('dealCodeNumber')
->get();
}))
->where('_id',$sid)
->get();