Laravel - pluck fields from relations - php

i'm new in laravel and php and now i wanna create a rest api
I have this query:
$questions = Question::with(
array('picture' => function($query){
$query>select('question_id','picture_name')>pluck('picture_name')>all();
},
'user'=>function($query){
$query->select('id','image','name');
}))->get()->toArray();
my query return this json:
{
"questions:": [
{
"id": 1,
"title": "23",
"caption": "last",
"address": "lsdbabfd",
"picture": [
{
"question_id": 1,
"picture_name": "1527484678.jpg"
},
{
"question_id": 1,
"picture_name": "1527485120.jpg"
}
],
"user": {
"id": 1,
"image": "defaultPicture",
"name": "alex"
}
}
]
}
but i want this json:
{
"questions:": [
{
"id": 1,
"title": "23",
"caption": "last",
"address": "lsdbabfd",
"picture": [
"1527484678.jpg",
"1527485120.jpg"
],
"user": {
"id": 1,
"image": "defaultPicture",
"name": "alex"
}
}
]
}
how can i do that?
i already tried to do that with Laravel pluck method and Eloquent Mutators

you can add attribute method
class Question extends Model
{
...
protected $appends = ['pictures'];
public function getPicturesAttribute()
{
return $this->pictures->pluck('picture_id');
}
}

Related

How to Count Nested Child from single table Laravel

Relation method
User model:
public function children()
{
return $this->hasMany(self::class, 'referrer_id')->with('children');
}
Controller Method:
$user = User::with('children')->where('id',$this->request->UserId)->get();
Response
{
"status": true,
"status_code": "Success",
"message": true,
"payload": {
"profile": [
{
"id": 1,
"referrer_id": null,
"name": "beciwerugy",
"username": "lahaky",
"email": "figo#mailinator.com",
"children": [
{
"id": 3,
"referrer_id": 1,
"name": "asd",
"username": "asde",
"email": "asda#asd.com",
"children": [
{
"id": 4,
"referrer_id": 3,
"name": "asd",
"username": "asde12",
"email": "as12a#asd.com",
]
}
]
}
]
}
]
}
]
}
}
I want to count all nestedchild at once
Currently im getting all nested child in ther list
but i just want count

Laravel hasMany relationship custom select result empty

I have tables, users, profiles, contacts. 1 user has 1 profile, 1 profile has many contacts, I want to get profile with filtered contact and selected column (I don't want get all column). I success with coding below
UserController.php
$profile = $user->with(['profile.emails', 'profile.phones'])->first();
User.php
public function profile()
{
return $this->hasOne(Profile::class);
}
Profile.php
public function emails()
{
return $this->hasMany(Contact::class)
->where('type', 'email');
}
public function phones()
{
return $this->hasMany(Contact::class)
->where('type', 'phone');
}
result data like this
{
"username": "user",
"email": "user#mail.com",
"profile": {
"first_name": "Alex",
"last_name": "Ariana",
"emails": [
{
"id": 1,
"profile_id": 1,
"type": "email",
"prefix": "Personal",
"value": "alex#mail.com",
"is_primary": 0,
},
{
"id": 2,
"profile_id": 1,
"type": "email",
"prefix": "Business",
"value": "business#mail.com",
"is_primary": 1,
}
],
"phones": [
{
"id": 3,
"profile_id": 1,
"type": "phone",
"prefix": "45",
"value": "564637345345",
"is_primary": 1,
}
]
}
}
but then I add select on the relation like this
public function emails()
{
return $this->hasMany(Contact::class)
->select([DB::raw('IFNULL(prefix, "Email") AS type'), 'value AS url', 'is_primary'])
->where('type', 'email');
}
public function phones()
{
return $this->hasMany(Contact::class)
->select(['prefix', 'value AS number', 'is_primary'])
->where('type', 'phone');
}
then I got empty contact data like this
{
"id": 1,
"username": "user",
"email": "user#mail.com",
"profile": {
"first_name": "Alex",
"last_name": "Ariana",
"emails": [ ],
"phones": [ ]
}
}
Why this is happen?, if I access from user via hasManyThrough it works, but when I use hasMany, it result empty.

Laravel pass parameter to its distant relationship (translate children)

I have categories with id, parent_id, slug , pivot table category_language which columns are id,category_id,language_id,value
As you can see I can translate parent category, but can't send desired $lang_id to children translations, so each children having all translations
here is what I get:
{
"id": 1,
"parent_id": 0,
"slug": "personal-computers",
"created_at": "2019-12-27 15:05:31",
"updated_at": "2019-12-27 15:05:31",
"children": [
{
"id": 3,
"parent_id": 1,
"slug": "accessories-for-pc",
"created_at": "2019-12-27 15:05:32",
"updated_at": "2019-12-27 15:05:32",
"translations": [
{
"id": 1,
"code": "en",
"name": "English",
"pivot": {
"category_id": 3,
"language_id": 1,
"value": "Acc for PC",
"id": 7
}
},
{
"id": 2,
"code": "ru",
"name": "Русский",
"pivot": {
"category_id": 3,
"language_id": 2,
"value": "Аксессуары для ноутбуков и ПК",
"id": 8
}
},
{
"id": 3,
"code": "ro",
"name": "Romana",
"pivot": {
"category_id": 3,
"language_id": 3,
"value": "aksessuari-dlya-noutbukov-i-pk-ro",
"id": 9
}
}
]
}
],
"translations": [
{
"id": 1,
"code": "en",
"name": "English",
"pivot": {
"category_id": 1,
"language_id": 1,
"value": "PC",
"id": 1
}
}
]
}
Controller:
return Category::with('children')
->with(array('translations'=>function($query) use ($lang_id){
$query->where('language_id',$lang_id);
}))
->where('parent_id',0)->first();
Model
class Category extends Model
{ ..
public function translations()
{
return $this->belongsToMany('App\Models\Translation','category_language', 'category_id' ,'language_id' )->withPivot('value','id');
}
public function children()
{
return $this->hasMany( 'App\Models\Category' , 'parent_id' , 'id' )->with('translations');
}
}
you can add condition in children method
public function children()
{
return $this->hasMany( 'App\Models\Category' , 'parent_id' , 'id' )->with('translations')->where('language_id', 1);
}
Dry7 answer was close to the one I've implemented later, so I upvoted him.
Finally in model I've added: ...->where('language_id',helper_SetCorrectLangIdForQuery());
and function helper_SetCorrectLangIdForQuery is using global helper of Laravel request()->lang . If lang=enz, than it takes default language from another helper.

Yii 2 Active Record nested many to many relations

I have 4 table products, properties, property_items, property_product with relations like this
Product has many properties.
Property has many property_items.
Product has many property_items.
Property_product is intermediary table.
-- products --
Id name
1 Arrabiata
2 Bolognese
--properties --
Id name
1 Pasta type
2 Size
-- property_items --
Id name value property_id
1 Spinach spaghetti ..... 1
2 Linguine ..... 1
3 Spaghetti ..... 1
4 Small .... 2
5 Medium .... 2
6 Large ... 2
-- property_product --
product_id property_id property_item_id
1 1 1
1 1 2
1 2 4
1 2 6
2 1 2
2 1 3
2 2 5
I try use Gii to create those models with relations .
class Products extends \yii\db\ActiveRecord
{
//code
....
public function getProperties()
{
return $this->hasMany(Properties::className(), ['id' => 'property_id'])
->viaTable('property_product', ['product_id' => 'id']);
}
}
class Properties extends \yii\db\ActiveRecord
{
//code
...
public function getPropertyItems()
{
return $this->hasMany(PropertyItems::className(), ['property_id' => 'id']);
}
}
I want to query data with multi nested relation.
How can i create json response with below format in one active record query ?
[
{
"id": "1",
"name": "Arrabiata",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
]
},
],
},
{
"id": "2",
"name": "Bolognese",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "5",
"name": "Medium",
},
]
},
]
}]
I use this query but it took too much perfomance
Menus::find()->with(['products' => function ($query) {
$query->with(['properties']);
}])
->where(['>', 'status', 0])
->andWhere(['resid' => $id])->asArray()->all();;
foreach ($menus as &$menu) {
foreach ($menu['products'] as &$product) {
foreach ($product['properties'] as &$property) {
$propertyItems = PropertyItems::find()->where(['property_id' => $property['id']]
)
->leftJoin('property_product', 'property_items.id = property_product.property_item_id')
->where(['property_product.product_id' => $product['id'],
'property_product.property_id' => $property['id']])
->asArray()->all();
$property['propertyItems'] = $propertyItems;
}
}
}
If I use this query
Menus::find()->with(['products' => function ($query) {
$query->with(['properties' => function ($query) {
$query->with(['propertyItems']);
}
]);
}
])->asArray()->all();
But the result not same as i expected because all property_items will show up in properties instead of depend on relating with products via table "property_product"
[
{
"id": "1",
"name": "Arrabiata",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
{
"id": "5",
"name": "Medium",
},
]
},
],
},
{
"id": "2",
"name": "Bolognese",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
{
"id": "5",
"name": "Medium",
},
]
}
]
}]
Thanks in advance.
You have to override the function fields() of the Products and Properties models.
for example:
class Products extends ActiveRecord {
function fields(){
return ['properties'];
}
}
class Properties extends ActiveRecord {
function fields(){
return ['property_items'];
}
}

How to modify a laravel collection that has been groupedby

I have the following code which takes a collection of CallRecords and then applies groupBy them as well as a filter:
$Groups = $CallRecords->filter( function($CallRecord)
{
return isset($CallRecord->meta->reason_not_connected) && true;
})
->groupBy('meta.reason_not_connected');
return $Groups;
Which returns
"example": {
"Reached Voicemail - No Message": [
{
"id": "44",
"phone_number_id": "51",
},
{
"id": "55",
"phone_number_id": "31",
},
],
"Reached Voicemail - Left Message": [
{
"id": "19",
"phone_number_id": "11",
},
{
"id": "20",
"phone_number_id": "21",
},
]
}
How can I morph this collection to display counts like this:
"example": {
"Reached Voicemail - No Message": 2,
"Reached Voicemail - Left Message": 2
}

Categories