How does it works the Laravel 4 model relationships? - php

I wish to know how works the laravel 4 relationships in the model. This question is because i'm trying to get the rows from 2 tables with relation and not success till now.
class Products extends Eloquent {
protected $table = "Products";
protected $primaryKey = "ProductId";
public function plandetail()
{
return $this->belongsTo("PlanDetail", "PlanDetail.ProductId")->select( array("ProductId", "Order") );
}
public function getProductsPlan($dealerId)
{
return $this->with( "plandetail" )->where("Products.DealerId", $dealerId)->get();
}
} // end model
// In my controller
$product = new Products();
$products = $product->getProductsPlan($id);
foreach( $products as $product )
{
print_r($product); // prints only the rows from the Products table
// not the PlanDetail table.
}
In the output is just print the product records and not the PlanDetail table rows. Do i need to add a join with the PlanDetail table to get these rows?
This is one example row of what im getting now:
Products Object ( [table:protected] => Products [primaryKey:protected] => ProductId [errors:Products:private] => [rules:Products:private] => Array ( [ProductBaseId] => required|numeric [DealerId] => required|numeric [ProductName] => required|max:255 [DisplayName] => required|max:255 [Bullets] => required [Cost] => required|numeric [SellingPrice] => required|numeric [UseWebServicePricing] => required|boolean [Term] => required|numeric [Type] => required|numeric [Deductible] => required|numeric [VehiclePlan] => required|numeric [Mileage] => required|numeric [TireRotation] => required|numeric [Interval] => required|numeric [UseRangePricing] => required|boolean [IsTaxable] => required|boolean [NotRegulated] => required|boolean [CreatedOn] => required [CreatedBy] => required [ModifiedBy] => required [ModifiedOn] => required ) [connection:protected] => [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [original:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [relations:protected] => Array ( [plandetail] => ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [softDelete:protected] => )
Thanks in advance :)

It looks like there's a few things wrong here.
The belongsTo method expects the name of the relating model, and then the foreign key of that model on the Products table. It looks like your foreign key is actually on the relating model making this relationship either a hasOne or hasMany. In this case, since you say you are expecting 2 rows, I'm assuming hasMany.
Additionally, the second argument of this only expects the name of the column. It can already guess the name of the table because you gave it the relating model name.
With that in mind, this should be the relationship method you need.
public function plandetails()
{
return $this->hasMany("PlanDetail", "ProductId")->select( array("ProductId", "Order") );
}
And the other function should be modified a bit. When you use with and you need to query based on the relation, you should pass in an array where the key is the name of the relation and the value is a callback function which will allow you to modify the query which will grab the relating items.
public function getProductsPlan($dealerId)
{
return $this->with(array("plandetail", function($q) use ($dealerId)
{
$q->where('DealerID', $dealerId);
}))->get();
}
Now when you do this...
$product = new Products();
$products = $product->getProductsPlan($id);
This should work...
foreach( $products as $product ) {
foreach($product->plandetails as $plandetail) {
print_r($plandetail);
}
}
I also modified the relating function name so you would have to update your getProductsPlan function to reflect that when you use with. When you use hasMany, it makes more sense and is easier to read when you make the function name plural.

Related

json_encode loses some object values in php

I have an object $myObject; I'm trying to return php object as json, but it loses some data. This is how $myObject looks:
CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList Object
(
[priceListId:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 32
[amounts:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 1000
[1] => 2000
[2] => 3000
[3] => 4000
[4] => 5000
[5] => 6000
[6] => 7000
)
[amountsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[1000] => 0
[2000] => 1
[3000] => 2
[4000] => 3
[5000] => 4
[6000] => 5
[7000] => 6
)
[periods:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 10
[1] => 15
[2] => 20
[3] => 25
[4] => 30
)
[periodsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[10] => 0
[15] => 1
[20] => 2
[25] => 3
[30] => 4
)
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 7000
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 30
[prices:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[30] => Array
(
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
)
)
[settings:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings Object
(
[mode:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => credits
[preset:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] =>
[implementation:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => matrix
[defaults:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => Array
(
[period] =>
[amount] =>
)
)
)
After json_encode($myObject); new data looks like this (screenshot for better json view):
screenshot of returned json
Why information I wrote below is missing and how to access it?
Missing stuff:
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
The problem is json_encode can not access private properties.
Here are some workarounds you could do:
Convert the properties to be public
You could use a reflection class to convert the properties accessibility before you convert it
Example:
$refObject = new ReflectionObject( $obj );
$refProperty = $refObject->getProperty( 'property' );
$refProperty->setAccessible( true );
You could loop through the properties of the object using a Reflection object and call all the getters converting the object into an array structure that could be easily translated
Refelection Class Documentation

How do I retrieve an item from an PHP Object Array?

I want to retrieve quantities from this array.
invoice Object
(
[data:private] => Array
(
[i_status] => pend
[i_title] => 500 HLCoins , 500 HLCoins x8
[i_member] => 1
[i_items] => Array
(
[0] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 1
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[extra] =>
[opt_id] => 0
[associated] =>
[assocBought] =>
[groupRenewals] => 0
[methods] => Array
(
)
[k] => 0
[_tax] => 0
)
[1] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 8
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[opt_id] => 0
[groupRenewals] => 0
[methods] => Array
(
)
[_tax] => 0
)
)
[i_total] => 0
[i_date] => 1347217384
[i_return_uri] =>
[i_paid] => 0
[i_status_extra] => a:1:{s:4:"type";s:4:"zero";}
[i_discount] => 0
[i_temp] =>
[i_ordersteps] => 0
[i_noreminder] => 1
[i_renewal_ids] => Array
(
)
[i_po] =>
[i_notes] =>
[i_shipaddress] =>
[i_id] => 229
)
[takeAction] => 1
)
I've tried a bunch of codes like $invoice->quantity, $invoice[1]->quantity, $this->$invoice->quantity, but none of them seem to display.
It still does not display at all, I tried to print_r and that is the array it gave me.
All the variables are private which means you cannot access them from outside the object. Check out the class definition for the invoice class. There should be some function to get the quantities from the object, or else you could add such a feature to the class.
The whole point of this is separation of concerns. The class may change in the future and possibly not use the same structure, therefore you should use object functions to access the properties, do not access them directly as variables.
You can read more on this subject in the manual or in a book about object-oriented programming.
Seems like all the data is in a private property. You cannot access it from outside directly.
Read the documentation for the class. It should have some method you can call, like getQuantity(), that'll get you the data. It depends on how the class was written and how it is supposed to be used.

cakephp - one find() query to rule them all

I have the following model relationships defined:
class Publication extends AppModel {
var $name = 'Publication';
var $hasAndBelongsToMany = array(
'Author'=>array(
'className'=>'Author'
)
);
}
class Author extends AppModel {
var $name = 'Author';
var $hasAndBelongsToMany = array(
'Publication'=>array(
'className'=>'Publication'
)
);
var $belongsTo = array(
'College' => array (
'className' => 'College'
)
);
}
class College extends AppModel {
var $name = 'College';
var $hasMany = array(
'Department'=>array(
'className'=>'Department'
)
);
}
class Department extends AppModel {
var $name = 'Department';
var $belongsTo = array(
'College'=>array(
'className'=>'College'
)
);
}
The database tables are set up correctly (join tables for the HABTM, etc.). I am trying to find the one DB query to rule them all. I want to create a query that will find all of the publications with the associated authors, colleges, departments, etc. After getting data from a form, I have tried to run queries like this:
$conditions = array(
"Author.id" => $this->data['authors'],
"Publication.year" => $this->data['year']
);
$publications = $this->Publication->find('all', array('conditions' => $conditions));
This throws SQL errors saying that Author.id is not a valid field. Now, this is because a join with the 'authors' db table has not been completed by the time Author.id is being searched for. BUT, if I do this:
$pubs = $this->Publication->find('all', array('conditions' => $conditions));
then I get an array that has all of the Publications with all of the associated Authors (though, not the associated Colleges for some reason).
My question is this: what do I need to do to make the tables join before Author.id is searched for? I've attempted to use bindModel, containable, subqueries, but cannot get those to work for some reason (probably a ID10T error).
Thanks for any advice!
Edit:
The result of the following call:
$this->Publication->recursive = 2;
$pubs = $this->Publication->find('all');
are as follows:
Array (
[0] => Array (
[Publication] => Array ( [id] => 1 [title] => TestArticle [year] => 2011 [type_id] => 3 )
[Type] => Array ( [id] => 3 [type_name] => Journal Articles )
[Author] => Array (
[0] => Array ( [id] => 2 [firstname] => Jeremy [lastname] => Gustine [middle] => A [faculty] => 0 [college_id] => 4 [AuthorsPublication] => Array ( [id] => 3 [author_id] => 2 [publication_id] => 1 )
[College] => Array ( [id] => 4 [college_name] => Letters, Arts, and Sciences ) )
[1] => Array ( [id] => 3 [firstname] => George [lastname] => Obama [middle] => A [faculty] => 0 [college_id] => 6 [AuthorsPublication] => Array ( [id] => 2 [author_id] => 3 [publication_id] => 1 )
[College] => Array ( [id] => 6 [college_name] => School of Public Affairs ) )
[2] => Array ( [id] => 2 [firstname] => Jeremy [lastname] => Gustine [middle] => A [faculty] => 0 [college_id] => 4 [AuthorsPublication] => Array ( [id] => 1 [author_id] => 2 [publication_id] => 1 )
[College] => Array ( [id] => 4 [college_name] => Letters, Arts, and Sciences ) ) ) )
[1] => Array (
[Publication] => Array ( [id] => 2 [title] => TestBook [year] => 2010 [type_id] => 1 )
[Type] => Array ( [id] => 1 [type_name] => Books )
[Author] => Array (
[0] => Array ( [id] => 7 [firstname] => Sony [lastname] => Stuff [middle] => L [faculty] => 0 [college_id] => 5 [AuthorsPublication] => Array ( [id] => 4 [author_id] => 7 [publication_id] => 2 )
[College] => Array ( [id] => 5 [college_name] => Nursing and Health Science ) ) ) ) )
Hopefully that is somewhat readable...
Your second find is correct
i.e. $pubs = $this->Publication->find('all', array('conditions' => $conditions));
just above that try using recursive 2 (below code) to get related College too.
$this->Publication->recursive = 2;

php access object values

EDIT: Thanks everyone. I didn't even notice it was private lol, so I changed them from private to public, now it should be accessible... question now is how can I access the value of say 'backpackPosition'? thanks again!
TF2Inventory Object
(
[fetchDate] => 123456123
[items] => Array
(
[60] => TF2Item Object
(
[equipped] => Array
(
[scout] => 1
[sniper] => 1
[soldier] => 1
[demoman] => 1
[medic] => 1
[heavy] => 1
[pyro] => 1
[spy] => 1
)
[attributes] => Array
(
[0] => stdClass Object
(
[name] => custom employee number
[class] => set_employee_number
[value] => 0
)
[1] => stdClass Object
(
[name] => cannot trade
[class] => cannot_trade
[value] => 1
)
)
[backpackPosition] => 61
[className] => tf_wearable
[count] => 1
[defindex] => 170
[id] => 535518002
[level] => 20
[name] => Primeval Warrior
[quality] => unique
[slot] => misc
[tradeable] =>
[type] => Badge
)
[43] => TF2Item Object
(
[equipped] => Array
(
[scout] => 0
[sniper] => 0
[soldier] => 0
[demoman] => 0
[medic] => 0
[heavy] => 0
[pyro] => 0
[spy] => 0
)
[attributes] => Array
(
[0] => stdClass Object
(
[name] => cannot trade
[class] => cannot_trade
[value] => 1
)
)
[backpackPosition] => 44
[className] => tf_wearable
[count] => 1
[defindex] => 471
[id] => 535518003
[level] => 50
[name] => Proof of Purchase
[quality] => unique
[slot] => head
[tradeable] =>
[type] => Hat
)
[42] => TF2Item Object
(
[equipped] => Array
(
[scout] => 1
[sniper] => 1
[soldier] => 1
[demoman] => 1
[medic] => 1
[heavy] => 1
[pyro] => 1
[spy] => 1
)
[attributes] =>
[backpackPosition] => 43
[className] => tf_wearable
[count] => 1
[defindex] => 278
[id] => 541628464
[level] => 31
[name] => Horseless Headless Horsemann's Head
[quality] => unique
[slot] => head
[tradeable] =>
[type] => Hat
)
[59] => TF2Item Object
(
[equipped] => Array
(
[scout] => 0
[sniper] => 0
[soldier] => 0
[demoman] => 0
[medic] => 0
[heavy] => 0
[pyro] => 0
[spy] => 0
)
[attributes] => Array
(
[0] => stdClass Object
(
[name] => cannot trade
[class] => cannot_trade
[value] => 1
)
)
[backpackPosition] => 60
[className] => tf_wearable
[count] => 1
[defindex] => 115
[id] => 548155039
[level] => 10
[name] => Mildly Disturbing Halloween Mask
[quality] => unique
[slot] => head
[tradeable] =>
[type] => Holiday Hat
)
Private members are just that - private. Only the class they belong to can access them. If you want to be able to retrieve their values, you need to either make them protected (and thus available to parent and children classes) or public (available to all classes). Another option is to write some getters, functions that look like
public function get_slot() {
return $this->slot;
}
or use the __get() magic function to make a general getter that looks like
public function __get($name) {
return $this->$name;
}
More info can be found in the documentation at http://php.net/manual/en/language.oop5.visibility.php
Those items are only accessible by the object itself. You will have to modify the code for that class and provide an accessor method, or change their scope.
http://www.php.net/manual/en/language.oop5.properties.php
You will need accessor method on each object in order to access the values. Since they are private they can only be accessed within each of the classes they belong.
The private properties just can be accessed from inside the object itself. To access try to use $this->propertyName
This answer is for the scenario of trying to get around an imposed private data restriction, for instance if you are by chance working with a library which you don't have access to change the privilege level of the class member, then there is a work around. Presuming the object is serializable/unserializable then consider:
<?php
class SourceProtected {
private $foo = 'one';
protected $baz = 'two';
public $bar = 'three';
}
class SourceUnprotected {
public $foo = 'blah';
public $baz = 'two';
public $bar = 'three';
}
$protected = new SourceProtected();
$unprotected = new SourceUnprotected();
var_dump(serialize($protected), serialize($unprotected));
The output looks something like:
string(110) "O:15:"SourceProtected":3:{s:20:"?SourceProtected?foo";s:3:"one";s:6:"?*?baz";s:3:"two";s:3:"bar";s:5:"three";}"
string(92) "O:17:"SourceUnprotected":3:{s:3:"foo";s:4:"blah";s:3:"baz";s:3:"two";s:3:"bar";s:5:"three";}"
So one solution, is to create a duplicate class that changes the privilege level on the variables to all public. Then serialize the working object, convert*** the serialized class to your versions, then simply unserialize the string and you'll have a working object of your class type with unlimited access.
Obviously the convert method is where you'll have to do some foot work. You'll need to either build a generalized parser which can handle any case or you can code a hacky works just for your specific use case series of str_replaces.
you should see first object oriented php http://www.google.sk/url?sa=t&rct=j&q=object%20oriented%20php&source=web&cd=6&ved=0CGQQFjAF&url=http%3A%2F%2Ftalks.somabo.de%2F200703_montreal_oop.pdf&ei=k3EUT8HnGYHHswbi09A6&usg=AFQjCNEjsA2JgbGQfxnQ26XxTtFuHmvGIA&sig2=Vw4d7aD2GhulZYAM892EKA

Merge arrays from 2 SQL results

So i have a tags table setup in SQL
lists, lists_tags, tags
Each list can have multiple tags, and tags have two types genre and producer. Now if we are looking for all lists with tags 'action' these are the steps im following
SELECT GROUP_CONCAT(mini_lists_tags.list_id) AS list_ids
FROM (`mini_tags`)
LEFT JOIN `mini_lists_tags` ON `mini_lists_tags`.`tag_id` = `mini_tags`.`tag_id`
WHERE `mini_tags`.`tag_slug` = 'action'
That will return an array 1,2 for the ids of the list.
SELECT *
FROM (`mini_lists_anime`)
JOIN `mini_lists` ON `mini_lists`.`list_id` = `mini_lists_anime`.`list_id`
WHERE `mini_lists`.`list_id` IN ('1', '2')
AND `mini_lists`.`list_state` = 'active'
that gets all the lists in an array EXAMPLE:
Array
(
[0] => stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
[list_aired] => 1238623200
[list_age_rate] => PG-13 - Teens 13 or older
[user_id] => 1
[list_mal] => 5342
[list_category] => Anime
[list_type] => TV
[list_status] => Completed
[list_title] => Asura Cryin'
[list_alt_titles] => アスラクライン
[list_thumb] => 17071
[list_likes] => 0
[list_date] => 1300609723
[list_update] => 0
[list_state] => active
[list_info] =>
)
[1] => stdClass Object
(
[list_id] => 2
[list_episodes] => 26
[list_duration] => 23
[list_aired] => 1238623200
[list_age_rate] => PG-13 - Teens 13 or older
[user_id] => 1
[list_mal] => 329
[list_category] => Anime
[list_type] => TV
[list_status] => Completed
[list_title] => Planetes
[list_alt_titles] => プラネテス
[list_thumb] => 4822
[list_likes] => 0
[list_date] => 1300609723
[list_update] => 0
[list_state] => active
[list_info] =>
)
)
And then we get the tags
SELECT `mini_lists_tags`.`list_id`, `mini_tags`.`tag_type`, GROUP_CONCAT(mini_tags.tag_name) AS tag_names
FROM (`mini_lists_tags`)
INNER JOIN `mini_tags` ON `mini_tags`.`tag_id` = `mini_lists_tags`.`tag_id`
WHERE `mini_lists_tags`.`list_id` IN ('1', '2')
GROUP BY `mini_lists_tags`.`list_id`, `mini_tags`.`tag_type`
that gets all the tags in an array EXAMPLE:
Array
(
[0] => stdClass Object
(
[list_id] => 1
[tag_type] => Genre
[tag_names] => Supernatural,Action,Mecha
)
[1] => stdClass Object
(
[list_id] => 1
[tag_type] => Producers
[tag_names] => Seven Arcs
)
[2] => stdClass Object
(
[list_id] => 2
[tag_type] => Genre
[tag_names] => Romance,Action,Sci-fi,Comedy,Slice of Life,Drama,Space
)
[3] => stdClass Object
(
[list_id] => 2
[tag_type] => Producers
[tag_names] => Sunrise,Bandai Entertainment,Bandai Visual,Bang Zoom! Entertainment
)
)
Now the problem is I need to get them merged on the list_id so it returns something like this for each one.
stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
[list_aired] => 1238623200
[list_age_rate] => PG-13 - Teens 13 or older
[user_id] => 1
[list_mal] => 5342
[list_category] => Anime
[list_type] => TV
[list_status] => Completed
[list_title] => Asura Cryin'
[list_alt_titles] => アスラクライン
[list_thumb] => 17071
[list_likes] => 0
[list_date] => 1300609723
[list_update] => 0
[list_state] => active
[list_info] =>
[list_tags] => Array
(
[0] => stdClass Object
(
[tag_type] => Genre
[tag_names] => Mecha,Action,Supernatural
)
[1] => stdClass Object
(
[tag_type] => Producers
[tag_names] => Seven Arcs
)
)
)
Any advice is appreciated, i'm really lost. if there is better solution than this, i am all ears.
You can do another type of join that will return the parent item multiple times merged with each child object like so:
Array(
[0] => stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
...etc
[tag_type] => Genre
[tag_names] => Supernatural,Action,Mecha
...etc
)
[1] => stdClass Object
(
[list_id] => 1
[list_episodes] => 13
[list_duration] => 24
...etc
[tag_type] => Producers
[tag_names] => Seven Arcs
...etc
)
[2] => stdClass Object
(
[list_id] => 2
[list_episodes] => 26
[list_duration] => 23
...etc
[tag_type] => Genre
[tag_names] => Supernatural,Action,Mecha
...etc
)
[3] => stdClass Object
(
[list_id] => 2
[list_episodes] => 26
[list_duration] => 23
...etc
[tag_type] => Producers
[tag_names] => Seven Arcs
...etc
)
)
You will then need to loop through your results merging down the results into their child/parent relationships. This is because SQL always returns rows as results, not complex structures.
Although this is more complex to deal with, it's ususally less process intensive than making looped sql queries for each parent object (known as n+1 queries)

Categories