I have a join in laravel 5.1 and it works fine, however I am getting back an array with each result of my join. Is there a way I can get the results back with the join results a nested array inside of my main select query, or would this have to be something I do in PHP after getting the results back?
$single = $this->db->table($this->table)
->leftJoin("ootd_clothing", "ootd_clothing.ootd_id", "=" ,"$this->table.id")
->leftJoin("users", "users.id", "=", "$this->table.user_id")
->where("$this->table.slug", "=", $slug)
->select("$this->table.name AS ootd_name", "$this->table.image_path", "$this->table.slug", "$this->table.description", "users.name AS user_name", "ootd_clothing.item", "ootd_clothing.brand")
->get();
Result I'm getting:
array:5 [▼
0 => {#158 ▶}
1 => {#159 ▶}
2 => {#160 ▶}
3 => {#161 ▶}
4 => {#162 ▶}
]
Result I would like:
array:1 [
'id': 1,
'joinResults':array:5 [▼
0 => {#158 ▶}
1 => {#159 ▶}
2 => {#160 ▶}
3 => {#161 ▶}
4 => {#162 ▶}
]
]
Related
i have one question in laravel query and search that in google and can't find that
This is my query :
$data = DB::table('event')
->where('TU', '!=', null)
->where('TM', '!=', 180)
->leftJoin('market', 'event.event_id', '=', 'market.event_id')
->select([
'event.event_id as id',
'TU',
DB::raw('(TM*60+TS) as elapsed'),
'markets' => 'market.*'
])
->orderBy('event.time', 'ASC')
->get();
and my result is this :
Collection {#380 ▼
#items: array:3 [▼
0 => {#381 ▼
+"id": 629
+"TU": 0
+"elapsed": 1200
+"default": 1
+"group_name": "other"
+"api_updated_at": null
+"updated_at": "2020-01-31 11:16:11"
}
1 => {#382 ▶}
2 => {#385 ▶}
]
}
i want all columns from market table pushed in one index in result
like that :
Collection {#380 ▼
#items: array:3 [▼
0 => {#381 ▼
+"id": 629
+"TU": 0
+"elapsed": 1200
+"markets": array:3 [▼
0 => {#382 ▼
+"default": 1
+"group_name": "other"
+"api_updated_at": null
+"updated_at": "2020-01-31 11:16:11"
}
1 => {#383 ▶}
2 => {#384 ▶}
]
}
]
}
please help me for edit query in laravel
you can not use a field instead of many fields of one table in select. you can try use
->select([
'event.event_id as id',
'TU',
DB::raw('(TM*60+TS) as elapsed'),
'market.*'
])
or use with('market') instead of leftjoin
I am currently facing a problem using the query builder and a left join. What I want to achieve is select all columns from the Article-Entity and, using a left join with two conditions, "append" a field to that array. In the snippet you'll see the working query without a join and the query with the left join and their results.
I know you can use "getScalarResult", but that produces the result shown in the snippet as well - it prefixes all columns from table "Article". What I would want is that result without the "a_" prefixes.
I know you can list the table fields in the select statement, but I do not want that query to be static but rather have it dynamic for when the table structure might change.
// default query
return $this->createQueryBuilder('a')
->andWhere('a.publishedAt IS NOT NULL')
->andWhere('a.publishedAt <= CURRENT_TIMESTAMP()')
->andWhere('a.status = 2')
->orderBy('a.publishedAt', 'DESC')
->getQuery()
->getResult();
// default result
array:5 [
0 => Article {#723
-id: 18
-title: "Title!"
-slug: "slug"
-content: "content"
-image: "img.jpg"
-author: BackendUser {#817 ▶}
-status: 2
-publishedAt: DateTime #1536546264 {#720 ▶}
-ratingPositive: 1
-ratingNegative: 0
-articleRatings: PersistentCollection {#816 ▶}
#createdAt: DateTime #1539163998 {#715 ▶}
#updatedAt: DateTime #1539180102 {#709 ▶}
}
...
]
// Left-Join-Query:
return $this->createQueryBuilder('a')
->andWhere('a.publishedAt IS NOT NULL')
->andWhere('a.publishedAt <= CURRENT_TIMESTAMP()')
->andWhere('a.status = 2')
->leftJoin('App\Entity\Article\ArticleRating', 'ar', 'WITH', 'ar.article = a.id AND ar.user = ' . $userId)
->addSelect('ar.rating as userRating')
->orderBy('a.publishedAt', 'DESC')
->getQuery()
->getResult();
// Left Join Result
array:5 [
0 => array:2 [
0 => Article {#722 ▼
-id: 18
-title: "Title"
-slug: "Slug"
-content: "Content"
-image: "image.jpg"
-author: BackendUser {#817 ▶}
-status: 2
-publishedAt: DateTime #1536546264 {#689 ▶}
-ratingPositive: 1
-ratingNegative: 0
-articleRatings: PersistentCollection {#816 ▶}
#createdAt: DateTime #1539163998 {#737 ▶}
#updatedAt: DateTime #1539180102 {#732 ▶}
}
"userRating" => true
]
...
]
// getScalarResult - result
array:5 [▼
0 => array:12 [▼
"a_id" => 18
"a_title" => "Title"
"a_slug" => "slug"
"a_content" => "content"
"a_image" => "image.jpg"
"a_status" => 2
"a_publishedAt" => DateTime #1536546264 {#689 ▶}
"a_ratingPositive" => 1
"a_ratingNegative" => 0
"a_createdAt" => DateTime #1539163998 {#737 ▶}
"a_updatedAt" => DateTime #1539180102 {#732 ▶}
"userRating" => "1"
]
...
]
My desired outcome would look like something like this:
array:5 [
0 => Article {#722 ▼
-id: 18
-title: "Title"
-slug: "Slug"
-content: "Content"
-image: "image.jpg"
-author: BackendUser {#817 ▶}
-status: 2
-publishedAt: DateTime #1536546264 {#689 ▶}
-ratingPositive: 1
-ratingNegative: 0
-articleRatings: PersistentCollection {#816 ▶}
#createdAt: DateTime #1539163998 {#737 ▶}
#updatedAt: DateTime #1539180102 {#732 ▶}
-userRating- => true
}
...
]
I've created a collection like this :
Collection {#651 ▼
#items: array:3 [▼
0 => array:3 [▼
"orderId" => "402457"
"orderCreated" => DateTime {#656 ▶}
"foods" => array:2 [▶]
]
1 => array:3 [▼
"orderId" => "402457"
"orderCreated" => DateTime {#661 ▶}
"foods" => array:2 [▶]
]
2 => array:3 [▼
"orderId" => "402457"
"orderCreated" => DateTime {#665 ▶}
"foods" => array:2 [▶]
]
]
}
I demand to achieve collection like this (with Laravel collection):
Collection {#651 ▼
#items: array:3 [▼
0 => array:3 [▼
"orderId" => "402457"
"orderCreated" => DateTime {#656 ▶}
"foods" => array:6 [▶]
]
]
}
Because orderId and orderCreated are all the same in arrays. I need to make single array that collect orderId and orderCreated with all foods.
Any suggestion?
You can take the data from the first one and just combine all of the food items. For instance like this:
$new = collect([
'orderId' => $old->first()->orderId,
'orderCreated' => $old->first()->orderCreated,
'foods' => $old->pluck('foods')->flatten(1),
]);
The exact implementation will depend on how you built your initial collection.
I'am having problem looping through an array to get every teams score for the last 10 games played by a player. This is how I'm looping through this array:
$WarzoneLast10MatchesTeamScore = [];
foreach($warzoneLast10matches->Results->Teams as $idx => $stats){
$WarzoneLast10MatchesTeamScore[$idx]['Score'] = $stats->Score;
$WarzoneLast10MatchesTeamScore[$idx]['Id'] = $stats->Id;
}
The problem with this is it will give me an error because I'am trying to get the last 10 games played, so result has to be then Result[0], Result[1], and so on.
Here is what I mean:
+"Results": array:10 [▼
0 => {#17371 ▼
+"Links": {#13129 ▶}
+"Id": {#13130 ▶}
+"HopperId": "0e39ead4-383b-4452-bbd4-babb7becd82e"
+"MapId": "c89dae21-f206-11e4-a1c2-24be05e24f7e"
+"MapVariant": {#13121 ▶}
+"GameBaseVariantId": "42f97cca-2cb4-497a-a0fd-ceef1ba46bcc"
+"GameVariant": {#17372 ▶}
+"MatchDuration": "PT6M50.2813116S"
+"MatchCompletedDate": {#17367 ▶}
+"Teams": array:2 [▼
0 => {#17374 ▼
+"Id": 0
+"Score": 1
+"Rank": 1
}
1 => {#17375 ▼
+"Id": 1
+"Score": 0
+"Rank": 2
}
]
+"Players": array:1 [▶]
+"IsTeamGame": true
+"SeasonId": null
+"MatchCompletedDateFidelity": 1
}
1 => {#17378 ▶}
2 => {#17390 ▶}
3 => {#17402 ▶}
4 => {#17414 ▶}
5 => {#17426 ▶}
6 => {#17438 ▶}
7 => {#17450 ▶}
8 => {#17462 ▶}
9 => {#17474 ▶}
]
I obviously don't want to make 10 loops for each game then hard code the score for each game in my view.
How can I loop through the Results object, and then get the Teams->score and Teams->Id objects?
FYI
I know I can use collections like this:
public function getWarzoneLast10Matches($warzoneLast10matches) {
// Collect al the results for this array
$results = collect($warzoneLast10matches->Results);
$array = $results->map(function($item, $key) {
return [
'Gamertag' => $item->Players[0]->Player->Gamertag,
'MapId' => $item->MapId,
'GameBaseVariantId' => $item->GameBaseVariantId,
'Score' => $item->Teams[0]->Score,
'Score2' => $item->Teams[1]->Score,
'Id' => $item->Teams[0]->Id,
'Id2' => $item->Teams[1]->Id,
];
});
return $array;
}
But this will not work because in some games there is only 1 team, and if that happens, then it will throw me an error saying undefined offset 1, because there is no team 2. The other method I'am using on top wont give me errors.
It sound like you might need to make your function recursive.
Learn more about Recursion
I have this collection:
Collection {#604 ▼
#items: array:4 [▼
0 => CarsMark {#596 ▶}
1 => CarsMark {#594 ▶}
2 => CarsMark {#594 ▶}
3 => CarsMark {#595 ▶}
]
}
As you can see there is two the same items (594). How can i retrieve all items from with collection without the same items?
Use the collection's unique method:
$unique = $collection->unique();