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() [...]
Related
Pagination is returning blank on next page. The result gets found but lost when I go to next page. This is query in my controller
if($request->has('SearchBtn')){
$search = $request->input('Search');
$query = \App\User::join('suppliers', 'users.id' ,'=', 'suppliers.user_id')
->where('company', 'LIKE', "%{$search}%")
->paginate(1);
if($query->isEmpty()){
$query = \App\Keywords::join('users', 'users.id' ,'=', 'keywords.user_id')
->join('suppliers', 'users.id' ,'=', 'suppliers.user_id')
->where('Keyword', 'LIKE', "%{$search}%")
->paginate(1);
}
return view('/Buyers/SearchResult', compact('query'));
}
And this is dd($query)
Illuminate\Pagination\LengthAwarePaginator {#1238 ▼
#total: 2
#lastPage: 2
#items: Illuminate\Database\Eloquent\Collection {#1233 ▶}
#perPage: 1
#currentPage: 1
#path: "http://localhost:8000/Buyers/SearchResult"
#query: []
#fragment: null
#pageName: "page"
+onEachSide: 3
#options: array:2 [▶]
}
As you can see it finds pages but can show only first one. My guess is that it has something to do with join because queries without it work just fine with paginate(). I honestly don't know what to try or how to start debugging this. If I switch paginate() with get() everything is fine and the data is shown correctly.
This is dd($request)
Illuminate\Http\Request {#43 ▼
#json: null
#convertedFiles: []
#userResolver: Closure($guard = null) {#246 ▶}
#routeResolver: Closure() {#255 ▶}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45 ▶}
+request: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+query: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+server: Symfony\Component\HttpFoundation\ServerBag {#47 ▶}
+files: Symfony\Component\HttpFoundation\FileBag {#48 ▶}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46 ▶}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/Buyers/SearchResult"
#requestUri: "/Buyers/SearchResult?_token=RG7LzXrHaL4x2jHOoCHC3TLbUqs22XaJDjuulOCo&Search=company&SearchBtn="
#baseUrl: ""
#basePath: null
#method: "GET"
#format: null
#session: Illuminate\Session\Store {#269 ▶}
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
UPDATE 1.0:
The blank page was returned due to this statement if($request->has('SearchBtn')) however now I face a new problem when I search something I get correct number of pages and when I got to the next page page count goes up and it shows all the results from the database.
UPDATE 1.1
And I fixed that by appending search to the query like this
$query = \App\User::join('suppliers', 'users.id' ,'=', 'suppliers.user_id')
->where('company', 'LIKE', "%{$search}%")
->paginate(1)->appends(['Search'=>$search]);
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.
I have a simple logic which get All comments, then I get all subcomments for each comment and return this to Javascript (via AJAX), but it does not return whole response.
Controller:
$comments = $commentRepo->getPaginationPost(1, 0, $id);
foreach ($comments as &$comment) {
$subcomments = $commentRepo->getSubComments($comment->getId());
$comment->subComments = $subcomments;
}
$response = [
'comments' => $comments,
'id' => $id,
'totalPages' => $totalPages
];
return new JsonResponse($response);
If I dump($reponse); exit;, before return it looks like this:
ArticleController.php on line 194:
array:3 [
"comments" => array:1 [
0 => & Comment {#7263
-id: 168
-content: "Лошо е"
-person: User {#5420
#id: 3
-firstName: "testtt"
-favouriteArticles: PersistentCollection {#5653
-snapshot: []
-owner: User {#5420}
-association: array:19 [ …19]
-em: EntityManager {#3456 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#5424 …}
-isDirty: false
#collection: ArrayCollection {#5688
-elements: []
}
#initialized: true
}
#username: "test#test.com"
#usernameCanonical: "test#test.com"
#email: "test#test.com"
#emailCanonical: "test#test.com"
#enabled: true
#salt: null
#password: "$2y$13$.8Ky5Jj71PUsGD9E04nre./xClPVZ/Uiia40PTQjGmMAqOFpW2mwi"
#plainPassword: null
#lastLogin: DateTime {#5416
+"date": "2019-01-07 09:39:06.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
#confirmationToken: null
#passwordRequestedAt: null
#groups: null
#roles: []
}
-dateAdded: DateTime {#7260
+"date": "2019-01-09 11:02:35.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
-replyTo: 0
-postId: 8
+"subComments": []
}
]
"id" => "8"
"totalPages" => 2.0
]
But In JS if I console.log of returned data is:
here
Only subcomments are there and I cannot access content of comment.
You can not convert object to JSON automatically here.
So you need to prepare data for JSON as simple array which can convert to JSON. Also, It's bad idea to use requests to database inside foreach.
The problem is that your properties are protected and private, as denoted by the # and - signs.
The protected and private properties will not appear in your response so you would need to set the values manually using getter methods or make your properties public.
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'];
}
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;