Symfony Querybuilder left join merge arrays - php

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
}
...
]

Related

Laravel select left join all columns in new array index

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

How to get columns name from sql server view by Laravel

I am trying to get columns name from sql view, my view appear like this:
name type building_id
test type_test 5
test2 type2_test 6
I want to get names(name & type & building_id)
I tried Laravel function getColumnListing() but i get null array
Try this
\Illuminate\Support\Facades\DB::select('show columns from table_name');
// table_name must be db table name
Result
array:5 [▼
0 => {#309 ▼
+"Field": "id"
+"Type": "int(10) unsigned"
+"Null": "NO"
+"Key": "PRI"
+"Default": null
+"Extra": "auto_increment"
}
1 => {#311 ▼
+"Field": "name"
+"Type": "varchar(100)"
+"Null": "NO"
+"Key": ""
+"Default": null
+"Extra": ""
}
2 => {#312 ▶}
3 => {#313 ▶}
4 => {#314 ▶}
]

How to get Release Date from tmdb API on Laravel 5.4?

I am using Laravel PHP Framework, I'd like to use the tmdb package.
I can see release date in json. Here is screenshot
http://prntscr.com/f98ydy
But I want this in my view like I can get title with code:
{!! $movie->getTitle() !!}
How to get release date? I also tried with that code
{!! $movie->getReleaseDate() !!}
But showing me this error
Object of class DateTime could not be converted to string (View: C:\xampp\htdocs\hallofsound\resources\views\welcome.blade.php)
Here is my full Json output
ResultCollection {#1811 ▼
-page: 1
-totalPages: 36
-totalResults: 702
#data: array:20 [▼
"000000004255a5960000000012a0a3a3" => Movie {#1816 ▼
-adult: false
-backdropPath: "/aJn9XeesqsrSLKcHfHP4u5985hn.jpg"
-backdrop: BackdropImage {#1327 ▶}
-belongsToCollection: null
-budget: null
-genres: Genres {#1832 ▶}
-homepage: null
-id: 283995
-imdbId: null
-originalTitle: "Guardians of the Galaxy Vol. 2"
-originalLanguage: "en"
-overview: "The Guardians must fight to keep their newfound family together as they unravel the mysteries of Peter Quill's true parentage."
-popularity: 115.058584
-poster: PosterImage {#1837 ▶}
-posterPath: "/y4MBh0EjBlMuOzv9axM4qJlmhzz.jpg"
-productionCompanies: GenericCollection {#1331 ▶}
-productionCountries: GenericCollection {#1830 ▶}
-releaseDate: DateTime {#1840 ▶}
-revenue: null
-runtime: null
-spokenLanguages: GenericCollection {#1828 ▶}
-status: null
-tagline: null
-title: "Guardians of the Galaxy Vol. 2"
-voteAverage: 7.6
-voteCount: 1539
#alternativeTitles: GenericCollection {#1826 ▶}
#changes: GenericCollection {#1829 ▶}
#credits: CreditsCollection {#1821 ▶}
#images: Images {#1319 ▶}
#keywords: GenericCollection {#1824 ▶}
#lists: GenericCollection {#1820 ▶}
#releases: GenericCollection {#1316 ▶}
#release_dates: GenericCollection {#1822 ▶}
#similar: GenericCollection {#1819 ▶}
#translations: GenericCollection {#1825 ▶}
#reviews: null
#videos: Videos {#1831 ▶}
}
"000000004255a5a00000000012a0a3a3" => Movie {#1838 ▶}
"000000004255a5c90000000012a0a3a3" => Movie {#1863 ▶}
"000000004255a5ee0000000012a0a3a3" => Movie {#1888 ▶}
"000000004255a5f70000000012a0a3a3" => Movie {#1913 ▶}
"000000004255a51f0000000012a0a3a3" => Movie {#1937 ▶}
"000000004255a5240000000012a0a3a3" => Movie {#1962 ▶}
"000000004255a54d0000000012a0a3a3" => Movie {#1987 ▶}
"000000004255a5550000000012a0a3a3" => Movie {#2011 ▶}
"000000004255a57d0000000012a0a3a3" => Movie {#2035 ▶}
"000000004255aa840000000012a0a3a3" => Movie {#2058 ▶}
"000000004255aaac0000000012a0a3a3" => Movie {#2082 ▶}
"000000004255aab50000000012a0a3a3" => Movie {#2107 ▶}
"000000004255aadb0000000012a0a3a3" => Movie {#2133 ▶}
"000000004255aae00000000012a0a3a3" => Movie {#2158 ▶}
"000000004255aa080000000012a0a3a3" => Movie {#2182 ▶}
"000000004255aa110000000012a0a3a3" => Movie {#2207 ▶}
"000000004255aa360000000012a0a3a3" => Movie {#2232 ▶}
"000000004255aa5f0000000012a0a3a3" => Movie {#2257 ▶}
"000000004255aa640000000012a0a3a3" => Movie {#2282 ▶}
]
}
The JSON response is a collection. So you need to loop through it. See here
So maybe something like this:
foreach($movies as $movie)
{
var_dump($movie->getTitle());
}
Also the method getReleaseDate will return a DateTime object. To format it, you can probably do something like this:
$date = new DateTime($movie->getReleaseDate());
$result = $date->format('Y-m-d H:i:s');
or in Laravel, you can do this:
{!! $movie->getReleaseDate()->format('Y-m-d H:i:s') !!}

How to remove the same item from Collection laravel?

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();

Laravel Query Builder Join results

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 ▶}
]
]

Categories