How to get a value from a Array symfony2.8 - php

Hi everyone i'm looking for a way to get a value in a variable but i'm stuck with an array like
$prixArrayArticle = $article->getArticlePlateforme()->getValues();
dump($prixArrayArticle);
gives me
ReassortController.php on line 1149:
array:1 [▼
0 => ArticlePlateforme {#1469 ▼
-article: Article {#1321 ▶}
-plateforme: Plateforme {#1051 ▶}
-codeProduitGv: "365717 "
-fournisseurCommun: FournisseurAchatsAdherents {#1445 ▶}
-referenceFournisseur: "100050 "
-minimumCommande: 1
-colisage: 12
-qtePalette: 12
-decolisable: true
-stock: 182
-dateCreation: DateTime {#1326 ▶}
-present: true
-articleSubstitution: null
-prix: PersistentCollection {#1430 ▼
-snapshot: array:1 [ …1]
-owner: ArticlePlateforme {#1469}
-association: array:19 [ …19]
-em: EntityManager {#137 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#1261 …}
-isDirty: false
#collection: ArrayCollection {#1439 ▼
-elements: array:1 [▼
0 => Prix {#1412 ▼
-id: 4175988
-dateDebut: DateTime {#1325 ▶}
-dateFin: DateTime {#1324 ▶}
-prixNet: "4.970"
-prixVenteConseille: null
-quantiteMinimum: null
-type: "permanent"
-numeroPromo: null
-offreComplementaire: false
-minimumCommande: 0
-colisage: 0
-invisible: null
-present: true
}
]
}
#initialized: true
}
-prixPromo: PersistentCollection {#1399 ▶}
}
]
and this
$article = $requeteArticle->getQuery()->getSingleResult();
give me this
ReassortController.php on line 1129:
Article {#769 ▼
-id: 1000940
-nom: "FILM DE PAILLAGE FRAISES FRESAFILM 1M40X10M"
-nomCourt: "FILM PAILLAGE FRAISES 1M40X10M"
-gamme: 5
-ecoContribution: "0.00"
-ecoMobilier: "0.00"
-quantiteAchat: "1.00"
-nombreUvParUa: "1.00"
-prixVenteConseille: "9.50"
-present: true
-tauxTva: TauxTva {#908 ▶}
-marque: null
-articleGencod: PersistentCollection {#1007 ▶}
-sousFamille: SousFamille {#635 ▶}
-articlePlateforme: PersistentCollection {#960 ▶}
-uniteAchat: UniteConditionnement {#833 ▶}
-uniteVente: UniteConditionnement {#833 ▶}
}
how can i get the name value for example in a variable because the array only have one index and i really don't know how to get a value with this array

Assuming that the properties are protected and that you have getters for them in your ArticlePlateforme and Article class, you should be able to get them like that:
$articleName = $prixArrayArticle[0]->getArticle()->getNom();
Otherwise, if the properties are public, you could simply get them like:
$articleName = $prixArrayArticle[0]->article->nom;

Related

How can I get access to object properties (arraycollection)?

This is my object products:
array:1 [▼
0 => Products {#8662 ▼
-id: 5
-name: "lion"
-unique_id: "7726d59574"
-productgroup: PersistentCollection {#8763 ▼
-snapshot: array:2 [ …2]
-owner: Products {#8662}
-association: array:20 [ …20]
-em: EntityManager {#4326 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#8294 …}
-isDirty: false
#collection: ArrayCollection {#8666 ▼
-elements: array:2 [▼
0 => Productgroup {#8765 ▼
-id: 5
-name: "Mammals"
-unique_id: "12102400f9"
}
1 => Productgroup {#8769 ▼
-id: 7
-name: "Fish"
-unique_id: "f0fbfa5c19"
}
]
}
#initialized: true
}
}
]
When I create json file like this...
$result = $serializer->serialize($products, 'json');
...I get this result:
[{"id":5,"uniqueId":"7726d59574","name":"lion","productgroup":[{"id":5,"uniqueId":"12102400f9","name":"Mammals"},{"id":7,"uniqueId":"f0fbfa5c19","name":"Fish"}]}]
But the result that I need is only productgroup. So this is what I try to achieve:
[{"id":5,"uniqueId":"12102400f9","name":"Mammals"},{"id":7,"uniqueId":"f0fbfa5c19","name":"Fish"}]
This was my first approach:
$data = $products->productgroup;
$result = $serializer->serialize($data, 'json');
But I got the error message:
Notice: Trying to get property 'productgroup' of non-object
I thought, oh ok, this means, products is not an object, so I tried this:
foreach ($products as $product) {
$data = $product['productgroup'];
}
$result = $serializer->serialize($data, 'json');
But now I get the error:
Cannot use object of type App\Entity\Products as array
try to use something like this:
foreach ($products as $product) {
$data = $product->getProductGroup();
}
Method getProductGroup must exists into your entity, if not you can have something similar I think.

Laravel 5 get attribute from collection

I have a $location collection that looks like this:
Collection {#225 ▼
#items: array:5 [▼
0 => GoogleAddress {#336 ▼
-id: "ChIJjWwHAP72w0cR44_HJ-bRcJE"
-locationType: "ROOFTOP"
-resultType: array:1 [▶]
-formattedAddress: ""
-streetAddress: null
-intersection: null
-political: ""
-colloquialArea: null
-ward: null
-neighborhood: null
-premise: null
-subpremise: null
-naturalFeature: null
-airport: null
-park: null
-pointOfInterest: null
-establishment: null
-subLocalityLevels: AdminLevelCollection {#339 ▶}
-coordinates: Coordinates {#331 ▶}
-bounds: Bounds {#332 ▶}
-streetNumber: "21"
-streetName: ""
-subLocality: null
-locality: ""
-postalCode: ""
-adminLevels: AdminLevelCollection {#337 ▶}
-country: Country {#335 ▶}
-timezone: null
-providedBy: "google_maps"
}
1 => GoogleAddress {#344 ▶}
2 => GoogleAddress {#352 ▶}
3 => GoogleAddress {#360 ▶}
4 => GoogleAddress {#368 ▶}
]
}
So I am trying to get the formattedAddress like this:
$location[0]->formattedAddress
But I get the following error:
Cannot access private property
Geocoder\Provider\GoogleMaps\Model\GoogleAddress::$formattedAddress
Anyone can help me out here?
It's a collection Do it like this
$location->first()->formattedAddress
The variable is private, meaning you can only access it from within the same class. In this case, the class has a getter method called getFormattedAddress() you can use.
Source: https://github.com/geocoder-php/Geocoder/blob/master/src/Provider/GoogleMaps/Model/GoogleAddress.php#L182
Solution: $location->first()->getFormattedAddress()
And a bit of advice, if you don't understand the private part, you really should have a look at the PHP documentation on visibility: http://php.net/manual/en/language.oop5.visibility.php
First, try to get the first object with $model->first()
If not, try to use mutators:(Here an example)
public function getNameAttribute()
{
return $this->attributes['firstName'];
}

Doctrine object incomplete when no session cookie, why?

I've encountered a silly problem this morning and I struggle to find a decent solution. Maybe you can tip me...
I've this simple function in a entity repository, with a simple query:
public function findAvailabilityByDr($delivery_round_id) {
$qb = $this->_em->createQueryBuilder()
->select('partial dro.{id},
partial drp.{id, maxDeliveries, countDeliveries},
partial zdd.{id, day},
partial rer.{id, maxOrders, countOrders}')
->from($this->_entityName, 'dro')
->leftJoin('dro.parts', 'drp')
->leftJoin('drp.day', 'zdd')
->leftJoin('drp.relayRounds', 'rer')
->where('dro.id = :delivery_round_id')
->setParameters(array(
'delivery_round_id' => $delivery_round_id,
));
dump($qb->getQuery()->getOneOrNullResult());
die();
}
At the first load (with no session cookie created), I got an incomplete result:
DeliveryRound {#342 ▼
-id: 117
-endOfOrdersDate: DateTime {#346 ▶}
-parts: PersistentCollection {#428 ▼
-snapshot: array:2 [ …2]
-owner: DeliveryRound {#342}
-association: array:15 [ …15]
-em: EntityManager {#695 …11}
-backRefFieldName: "deliveryRound"
-typeClass: ClassMetadata {#373 …}
-isDirty: false
#collection: ArrayCollection {#412 ▼
-elements: array:2 [▼
0 => DeliveryRoundPart {#425 ▼
-id: 134
-deliveryDate: DateTime {#347 ▶}
-deliveryHourStart: null
-deliveryHourEnd: null
-maxDeliveries: null <------ HERE !!!!!!!!!!!
-countDeliveries: null
-deliveryRound: DeliveryRound {#342}
-day: ZoneDeliveryDay {#1302 ▶}
-ordersCustomers: PersistentCollection {#358 ▶}
-ordersProviders: PersistentCollection {#410 ▶}
-relayRounds: PersistentCollection {#637 ▶}
-roadSheetOptimizationData: null
}
1 => DeliveryRoundPart {#1444 ▶}
]
}
#initialized: true
}
-ordersProvidersGenDate: null
-roadSheetPath: null
-roadSheetGenDate: null
-preparationSheetPath: null
-preparationSheetGenDate: null
-deliveryMailNotificationsSendingDate: null
-deliveryNotificationsSendingDate: null
#translations: PersistentCollection {#420 ▶}
#newTranslations: null
#currentLocale: "fr"
#defaultLocale: "fr"
}
And at the second call (refresh), the session cookie is created and the result is correct (maxDeliveries: 30 is a correct value):
DeliveryRound {#1657 ▼
-id: 117
-endOfOrdersDate: null
-parts: PersistentCollection {#1794 ▼
-snapshot: array:2 [ …2]
-owner: DeliveryRound {#1657}
-association: array:15 [ …15]
-em: EntityManager {#695 …11}
-backRefFieldName: "deliveryRound"
-typeClass: ClassMetadata {#1673 …}
-isDirty: false
#collection: ArrayCollection {#1795 ▼
-elements: array:2 [▼
0 => DeliveryRoundPart {#1747 ▼
-id: 134
-deliveryDate: null
-deliveryHourStart: null
-deliveryHourEnd: null
-maxDeliveries: 30 <------ HERE !!!!!!!!!!!
-countDeliveries: 0
-deliveryRound: DeliveryRound {#1657}
-day: ZoneDeliveryDay {#2063 ▶}
-ordersCustomers: PersistentCollection {#1904 ▶}
-ordersProviders: PersistentCollection {#1896 ▶}
-relayRounds: PersistentCollection {#2187 ▶}
-roadSheetOptimizationData: null
}
1 => DeliveryRoundPart {#2188 ▶}
]
}
#initialized: true
}
-ordersProvidersGenDate: null
-roadSheetPath: null
-roadSheetGenDate: null
-preparationSheetPath: null
-preparationSheetGenDate: null
-deliveryMailNotificationsSendingDate: null
-deliveryNotificationsSendingDate: null
#translations: PersistentCollection {#1799 ▶}
#newTranslations: null
#currentLocale: "fr"
#defaultLocale: "fr"
}
And when I use $qb->getQuery()->getArrayResult()
the results are correct in both cases.
WTF ? Is it bug ?
Thanks for your help !
EDIT
If I reduce it to its simplest expression, with no partial and a call from a controller, the bug is still there...
Repository:
public function findAvailabilityByDr($delivery_round_id) {
$qb = $this->_em->createQueryBuilder()
->select('dro,
drp')
->from($this->_entityName, 'dro')
->leftJoin('dro.parts', 'drp')
->where('dro.id = :delivery_round_id')
->setParameters(array(
'delivery_round_id' => $delivery_round_id,
));
return $qb->getQuery()->getOneOrNullResult();
}
Controller:
class StructureController extends BasePublicCommonController
{
public function indexAction()
{
$delivery_round = $this->getDoctrine()->getManager()->getRepository('ProxymartDeliveryBundle:DeliveryRound')->findAvailabilityByDr(117);
dump($delivery_round);
die();
}
}
This is for things like this I hate programming sometimes :)
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/partial-objects.html
I don't know about the cookie, but I know for arrayResult():
The partial object problem in general does not apply to methods or queries where you do not retrieve the query result as objects. Examples are: Query#getArrayResult() [...]

Laravel 5 Query Builder not returning any data

I have some nested query in my application such as example follow.
$arrData = DB::table('service as tsv')
->select($afields)
->join('shops as ts', 'ts.id', '=', 'tsv.shop_id')
->where('ts.name','like','%'.$searchstring.'%');
if(!empty($type) && $type == 'individual')
$arrData->where('ts.type','=', '1');
$arrData->groupBy('tsv.id')->get();
This query not returning the exact output it display the content like
Builder {#351 ▼
#connection: MySqlConnection {#336 ▶}
#grammar: MySqlGrammar {#347 ▶}
#processor: MySqlProcessor {#348}
#bindings: array:5 [▶]
+aggregate: null
+columns: array:7 [▶]
+distinct: false
+from: "service as tsv"
+joins: array:3 [▶]
+wheres: array:3 [▶]
+groups: array:1 [▶]
+havings: null
+orders: array:1 [▶]
+limit: 4
+offset: 0
+unions: null
+unionLimit: null
+unionOffset: null
+unionOrders: null
+lock: null
#backups: []
#operators: array:26 [▶]
#useWritePdo: false
}
I want to display the data how should I access the data from this situation.

Repository Entity not found in symfony2

I'm developing two projects with Symfony2, and I began to code the second project and I'm facing some problems with Custom functions to search in my tables.
This is my Sites Entity
namespace Ad\SisBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Sites
*
* #ORM\Table(name="sites")
* #ORM\Entity(repositoryClass="Ad\SisBundle\Entity\SitesRepository")
*/
class Sites
{
This is my SitesRepository Entity
namespace Ad\SisBundle\Entity;
use Doctrine\ORM\EntityRepository;
class SitesRepository extends EntityRepository
{
The problem is that I can't access any function that I create in my SitesRepository
I was dumping the doctrine EntityRepository Class and I saw this.
EntityRepository {#309 ▼
#_entityName: "Ad\SisBundle\Entity\Sites"
#_em: EntityManager {#289 …10}
#_class: ClassMetadata {#298 ▼
+name: "Ad\SisBundle\Entity\Sites"
+namespace: "Ad\SisBundle\Entity"
+rootEntityName: "Ad\SisBundle\Entity\Sites"
+customGeneratorDefinition: null
+customRepositoryClassName: null
+isMappedSuperclass: false
+parentClasses: []
+subClasses: []
+namedQueries: []
+namedNativeQueries: []
+sqlResultSetMappings: []
+identifier: array:1 [▶]
+inheritanceType: 1
+generatorType: 4
+fieldMappings: array:5 [▶]
+fieldNames: array:5 [▶]
+columnNames: array:5 [▶]
+discriminatorValue: null
+discriminatorMap: []
+discriminatorColumn: null
+table: array:1 [▶]
+lifecycleCallbacks: []
+entityListeners: []
+associationMappings: []
+isIdentifierComposite: false
+containsForeignIdentifier: false
+idGenerator: IdentityGenerator {#306 ▶}
+sequenceGeneratorDefinition: null
+tableGeneratorDefinition: null
+changeTrackingPolicy: 1
+isVersioned: null
+versionField: null
+reflClass: ReflectionClass {#307 ▶}
+isReadOnly: false
#namingStrategy: DefaultNamingStrategy {#276}
+reflFields: array:5 [▶]
-_prototype: null
}
}
So I went to my first project, that is working perfectly, and did the same thing.
ScheduleRepository {#1931 ▼
#_entityName: "ApplicationBundle\Entity\Schedule"
#_em: EntityManager {#137 …10}
#_class: ClassMetadata {#1825 ▼
+name: "ApplicationBundle\Entity\Schedule"
+namespace: "ApplicationBundle\Entity"
+rootEntityName: "ApplicationBundle\Entity\Schedule"
+customGeneratorDefinition: null
+customRepositoryClassName: "ApplicationBundle\Entity\ScheduleRepository"
+isMappedSuperclass: false
+parentClasses: []
+subClasses: []
+namedQueries: []
+namedNativeQueries: []
+sqlResultSetMappings: []
+identifier: array:1 [▶]
+inheritanceType: 1
+generatorType: 4
+fieldMappings: array:3 [▶]
+fieldNames: array:3 [▶]
+columnNames: array:3 [▶]
+discriminatorValue: null
+discriminatorMap: []
+discriminatorColumn: null
+table: array:2 [▶]
+lifecycleCallbacks: array:2 [▶]
+entityListeners: []
+associationMappings: array:2 [▶]
+isIdentifierComposite: false
+containsForeignIdentifier: false
+idGenerator: IdentityGenerator {#1852 ▶}
+sequenceGeneratorDefinition: null
+tableGeneratorDefinition: null
+changeTrackingPolicy: 1
+isVersioned: null
+versionField: null
+reflClass: ReflectionClass {#1840 ▶}
+isReadOnly: false
#namingStrategy: DefaultNamingStrategy {#119}
+reflFields: array:5 [▶]
-_prototype: null
}
}
In my Schedule Entity from project #1 I have the customRepositoryClassName filled, but in my Sites Entity not. Why? The both use the same version of doctrine and symfony.
I saw that the dump in project #1 is dumping ScheduleRepository and project #2 is dumping EntityRepository. Maybe this is the problem?
Project #1 dump:
$em = $this->getDoctrine()->getManager();
dump( $em->getRepository( "ApplicationBundle:Schedule" ) );exit;
Project #2 dump:
$em = $this->getDoctrine()->getManager();
dump( $em->getRepository( "AdSisBundle:Sites" ) );exit;
The entities from project #2 was created using: http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html
That is the only difference between the both projects.
Thank you for the help.

Categories