0

I've been working with Laravel Eloquent, now I want to write RAW query and get data with it.

My Query(Eloquent) is this:

 $jobs = CompanyJob::where('fair_id',$fair_id);
        
    $jobs = $jobs->with('company');
    // dd($jobs->toSql());
 
    if (!empty($jobIds)) {
      $jobs = $jobs->whereIn('id',$jobIds);
    }
    $jobs = $jobs->orderBy('id', 'ASC');
    if(isset($search) && !empty($search))
      $jobs = $jobs->where(function($query) use($search){
        $query->where('title','LIKE','%'.$search.'%')->OrWhere('location','LIKE','%'.$search.'%');
      });

    if (!empty($limit)) {
      $jobs = $jobs->limit($limit);
      $jobs = $jobs->offset($offset);
    }

    $jobs = $jobs->get();

The result from this query is :

{
    "jobs": [
        {
            "id": 6381,
            "company_id": "1507",
            "fair_id": "118",
            "recruiter_id": "147143",
            "title": "Master of Arts in Entrepreneurship for the Global Hospitality and Tourism Industry",
            "description": "<p><span style=\"font-weight: 400;\">H&auml;r kan du hitta mer information om utbildningen!</span><span style=\"font-weight: 400;\"><br /><br /></span></p>",
            "job_type": "Permanent",
            "language": "English",
            "location": "Brig",
            "contact_name": null,
            "phone": null,
           
            "url": "https://www.studentum.se/skola/swiss-education-group/cesar-ritz-colleges/master-of-arts-in-entrepreneurship-for-the-global-hospitality-and-tourism-industry-969435",
            "salary": "Competitive",
            "match": "1",
            "status": null,
            "params": null,
            "is_imported": "N",
            "questionnaires_template_id": "0",
            "import_ref": null,
            "imported_from": null,
            "match_index": "N",
            "last_offset": null,
            "total_records_to_index": null,
            "created_at": "2021-02-27 17:22:24",
            "updated_at": "2021-02-27 17:22:24",
            "company": {
                "id": 1507,
                "admin_id": null,
                "fair_id": "118",
                "recruiter_id": "147136",
                "company_name": "Swiss Education Group",
              
                "company_post_code": "111",
                "company_state": "Göteborg",
                "company_country": "Sverige",
                "company_match": "1",
                "company_web_url": "https://www.studentum.se/skola/swiss-education-group/",
                "company_facebook_url": null,
                "company_youtube_url": null,
                "company_twitter_url": null,
                "company_in_url": null,
                "company_instagram_url": null,
                "company_stand_type": "Bronze",
                "description": "<p><span style=\"font-weight: 400;\">Vilka &auml;r vi?</span></p>\r\n<p>&nbsp;</p>\r\n<p><span style=\"font-weight: 400;\">Swiss Education Group (SEG) &auml;r en av v&auml;rldens ledande leverant&ouml;rer av Hotell Management, kock -och konditorutbildningar i Schweiz. V&aring;ra utbildningar &auml;r till f&ouml;r studenter som vill ha en internationell karri&auml;r som hotellchef, kock, konditor eller n&aring;got annat yrke inom just servicebranschen.</span></p>\r\n<p>&nbsp;</p>\r\n<p><span style=\"font-weight: 400;\">Vi driver totalt fyra skolor p&aring; olika campus i Schweiz:</span></p>\r\n<p><span style=\"font-weight: 400;\">- Swiss Hotel Management School</span></p>\r\n<p><span style=\"font-weight: 400;\">- Culinary Arts Academy Switzerland</span></p>\r\n<p><span style=\"font-weight: 400;\">- Hotel Institute Montreux</span></p>\r\n<p><span style=\"font-weight: 400;\">- C&eacute;sar Ritz Colleges Switzerland</span></p>\r\n<p>&nbsp;</p>\r\n<p><span style=\"font-weight: 400;\">Samarbeten med branschen</span></p>\r\n<p>&nbsp;</p>\r\n<p><span style=\"font-weight: 400;\">Samtliga skolor som ing&aring;r i v&aring;rt n&auml;tverk, &auml;r akademiskt ackrediterade och har etablerade samarbeten med m&aring;nga av branschens ledande f&ouml;retag och varum&auml;rken. N&aring;gra f&aring; exempel p&aring; samarbeten &auml;r: Four Seasons, Ritz Paris, Marriott International samt lyxrestauranger v&auml;rlden &ouml;ver. Detta ger studenten en utbildning som &auml;r direkt anknuten till vad den internationella hotellbranschen efterfr&aring;gar.</span></p>\r\n<p>&nbsp;</p>\r\n<p><span style=\"font-weight: 400;\">Swiss Education Group (SEG) &auml;r en av v&auml;rldens fr&auml;msta n&auml;tverk av skolor inom 'hospitality management'. N&auml;tverkets framg&aring;ng har lett till att den internationella hotellbranschen nu st&auml;ller allt h&ouml;gre krav p&aring; sina medarbetare. Man kan verkligen s&auml;ga att SEG har h&ouml;jt ribban f&ouml;r kvaliteten p&aring; anst&auml;llda inom hospitality management.</span></p>",
                "company_logo": "assets/images/user-id-48854_SEG-logga.png",
                "company_stand_image": "assets/images/user-id-48854_SEG-logga.png",
                "company_stand_banner": "assets/images/user-id-48854_SEG-roll.jpg",
                "dashboard_thumbnail": null,
                "company_hall": "2",
                "questionnaire_selected": "0",
                "enable_recruiters": "1",
                "enable_webinars": "0",
                "enable_goodies": "0",
                "enable_media": "1",
                "enable_jobs": "1",
                "enable_documents": "1",
                "enable_about": "1",
                "enable_auto_enrolled": "0",
                "enable_poll": "0",
                "display_order": "0",
                "created_at": "2021-02-27 16:59:10",
                "updated_at": "2021-02-27 16:59:10"
            }
        },
        {
            "id": 6480,
            "company_id": "1521",
            "fair_id": "118",
            "recruiter_id": "147575",
            "title": "Master of Arts in Entrepreneurship for the Global Hospitality and Tourism Industry",
            "description": "<p><span style=\"font-weight: 400;\">H&auml;r kan du hitta mer information om utbildningen!</span><span style=\"font-weight: 400;\">&nbsp;</span></p>",
            "job_type": "Permanent",
            "language": "English",
            "location": "Brig",
            "contact_name": null,
            "phone": null,
        
            "url": "https://www.studentum.se/skola/swiss-education-group/cesar-ritz-colleges/master-of-arts-in-entrepreneurship-for-the-global-hospitality-and-tourism-industry-969435",
            "salary": "Competitive",
            "match": "1",
            "status": null,
            "params": null,
            "is_imported": "N",
            "questionnaires_template_id": "0",
            "import_ref": null,
            "imported_from": null,
            "match_index": "N",
            "last_offset": null,
            "total_records_to_index": null,
            "created_at": "2021-03-01 00:39:05",
            "updated_at": "2021-03-01 00:39:05",
            "company": {
                "id": 1521,
                "admin_id": null,
                "fair_id": "118",
                "recruiter_id": null,
                "company_name": "Swiss Education Group",
         
                "company_post_code": "111",
                "company_state": "Malmö",
                "company_country": "Sverige",
                "company_match": "1",
                "company_web_url": "https://www.studentum.se/skola/swiss-education-group/",
                "company_facebook_url": null,
                "company_youtube_url": null,
                "company_twitter_url": null,
                "company_in_url": null,
                "company_instagram_url": null,
                "company_stand_type": "Bronze",
                "description": "<p>Vilka &auml;r vi? <br /> <br /> Swiss Education Group (SEG) &auml;r en av v&auml;rldens ledande leverant&ouml;rer av Hotell Management, kock -och konditorutbildningar i Schweiz. V&aring;ra utbildningar &auml;r till f&ouml;r studenter som vill ha en internationell karri&auml;r som hotellchef, kock, konditor eller n&aring;got annat yrke inom just servicebranschen. <br /> <br /> Vi driver totalt fyra skolor p&aring; olika campus i Schweiz: <br /> - Swiss Hotel Management School <br /> - Culinary Arts Academy Switzerland <br /> - Hotel Institute Montreux <br /> - C&eacute;sar Ritz Colleges Switzerland <br /> <br /> Samarbeten med branschen <br /> <br /> Samtliga skolor som ing&aring;r i v&aring;rt n&auml;tverk, &auml;r akademiskt ackrediterade och har etablerade samarbeten med m&aring;nga av branschens ledande f&ouml;retag och varum&auml;rken. N&aring;gra f&aring; exempel p&aring; samarbeten &auml;r: Four Seasons, Ritz Paris, Marriott International samt lyxrestauranger v&auml;rlden &ouml;ver. Detta ger studenten en utbildning som &auml;r direkt anknuten till vad den internationella hotellbranschen efterfr&aring;gar. <br /> <br /> Swiss Education Group (SEG) &auml;r en av v&auml;rldens fr&auml;msta n&auml;tverk av skolor inom 'hospitality management'. N&auml;tverkets framg&aring;ng har lett till att den internationella hotellbranschen nu st&auml;ller allt h&ouml;gre krav p&aring; sina medarbetare. Man kan verkligen s&auml;ga att SEG har h&ouml;jt ribban f&ouml;r kvaliteten p&aring; anst&auml;llda inom hospitality management. <br /> </p>",
                "company_logo": "assets/images/user-id-48854_SEG-logga.png",
                "company_stand_image": "assets/images/user-id-48854_SEG-logga.png",
                "company_stand_banner": "assets/images/user-id-48854_SEG-roll.jpg",
                "dashboard_thumbnail": null,
                "company_hall": "3",
                "questionnaire_selected": "0",
                "enable_recruiters": "1",
                "enable_webinars": "0",
                "enable_goodies": "0",
                "enable_media": "1",
                "enable_jobs": "1",
                "enable_documents": "1",
                "enable_about": "1",
                "enable_auto_enrolled": "0",
                "enable_poll": "0",
                "display_order": "0",
                "created_at": "2021-03-01 00:13:26",
                "updated_at": "2021-03-01 00:13:26"
            }
        },
        {
            "id": 6520,
            "company_id": "1528",
            "fair_id": "118",
            "recruiter_id": "147609",
            "title": "Master of Arts in Entrepreneurship for the Global Hospitality and Tourism Industry",
            "description": "<p><span style=\"font-weight: 400;\">H&auml;r kan du hitta mer information om utbildningen!</span> <span style=\"font-weight: 400;\">&nbsp;</span></p>",
            "job_type": "Permanent",
            "language": "English",
            "location": "Brig",
            "contact_name": null,
            "phone": null,
         
            "url": "https://www.studentum.se/skola/swiss-education-group/cesar-ritz-colleges/master-of-arts-in-entrepreneurship-for-the-global-hospitality-and-tourism-industry-969435",
            "salary": "Competitive",
            "match": "1",
            "status": null,
            "params": null,
            "is_imported": "N",
            "questionnaires_template_id": "0",
            "import_ref": null,
            "imported_from": null,
            "match_index": "N",
            "last_offset": null,
            "total_records_to_index": null,
            "created_at": "2021-03-01 01:29:33",
            "updated_at": "2021-03-01 01:29:33",
            "company": {
                "id": 1528,
                "admin_id": null,
                "fair_id": "118",
                "recruiter_id": null,
                "company_name": "Swiss Education Group",
        
                "company_post_code": "111",
                "company_state": "Stockholm",
                "company_country": "Sverige",
                "company_match": "1",
                "company_web_url": "https://www.studentum.se/skola/swiss-education-group/",
                "company_facebook_url": null,
                "company_youtube_url": null,
                "company_twitter_url": null,
                "company_in_url": null,
                "company_instagram_url": null,
                "company_stand_type": "Bronze",
                "description": "<p>Vilka &auml;r vi? <br /> <br /> Swiss Education Group (SEG) &auml;r en av v&auml;rldens ledande leverant&ouml;rer av Hotell Management, kock -och konditorutbildningar i Schweiz. V&aring;ra utbildningar &auml;r till f&ouml;r studenter som vill ha en internationell karri&auml;r som hotellchef, kock, konditor eller n&aring;got annat yrke inom just servicebranschen. <br /> <br /> Vi driver totalt fyra skolor p&aring; olika campus i Schweiz: <br /> - Swiss Hotel Management School <br /> - Culinary Arts Academy Switzerland <br /> - Hotel Institute Montreux <br /> - C&eacute;sar Ritz Colleges Switzerland <br /> <br /> Samarbeten med branschen <br /> <br /> Samtliga skolor som ing&aring;r i v&aring;rt n&auml;tverk, &auml;r akademiskt ackrediterade och har etablerade samarbeten med m&aring;nga av branschens ledande f&ouml;retag och varum&auml;rken. N&aring;gra f&aring; exempel p&aring; samarbeten &auml;r: Four Seasons, Ritz Paris, Marriott International samt lyxrestauranger v&auml;rlden &ouml;ver. Detta ger studenten en utbildning som &auml;r direkt anknuten till vad den internationella hotellbranschen efterfr&aring;gar. <br /> <br /> Swiss Education Group (SEG) &auml;r en av v&auml;rldens fr&auml;msta n&auml;tverk av skolor inom 'hospitality management'. N&auml;tverkets framg&aring;ng har lett till att den internationella hotellbranschen nu st&auml;ller allt h&ouml;gre krav p&aring; sina medarbetare. Man kan verkligen s&auml;ga att SEG har h&ouml;jt ribban f&ouml;r kvaliteten p&aring; anst&auml;llda inom hospitality management. <br /> </p>",
                "company_logo": "assets/images/user-id-48854_SEG-logga.png",
                "company_stand_image": "assets/images/user-id-48854_SEG-logga.png",
                "company_stand_banner": "assets/images/user-id-48854_SEG-roll.jpg",
                "dashboard_thumbnail": null,
                "company_hall": "1",
                "questionnaire_selected": "0",
                "enable_recruiters": "1",
                "enable_webinars": "0",
                "enable_goodies": "0",
                "enable_media": "1",
                "enable_jobs": "1",
                "enable_documents": "1",
                "enable_about": "1",
                "enable_auto_enrolled": "0",
                "enable_poll": "0",
                "display_order": "0",
                "created_at": "2021-03-01 01:19:58",
                "updated_at": "2021-03-01 01:19:58"
            }
        }
    ]
}

I want to write RAW query for this, first i used $jobs->toSlq() but this didn't give me query of with() So I searched and found that for this I have to use

DB::enableQueryLog(); and DB::getQueryLog();

Then I got following result:

array:2 [
  0 => array:3 [
    "query" => "select * from `company_jobs` where `fair_id` = ? and (`title` LIKE ? or `location` LIKE ?) order by `id` asc"
    "bindings" => array:3 [
      0 => "118"
      1 => "%the%"
      2 => "%the%"
    ]
    "time" => 4.88
  ]
  1 => array:3 [
    "query" => "select * from `companies` where `companies`.`id` in (?, ?, ?)"
    "bindings" => array:3 [
      0 => "1507"
      1 => "1521"
      2 => "1528"
    ]
    "time" => 0.27
  ]
]

Still I'm not able to understand how to write query to get data as above is given. How will I get companies.id in raw query and how companies record will be join with jobs data etc? Can anyone help me to write Eloquent query in RAW SQL query? I also want to know how with() works in Laravel?

Relations of Models are:

Job->belongsTo('Company') and
Company->hasMany('CompanyJob')
Ali Bhutta
  • 457
  • 5
  • 20
  • 1
    You do the first query alone, THEN you take the results from the first query and run a second one. The eager loading work like that. You get to join table when using `whereHas()` – N69S Mar 24 '21 at 09:07
  • how first query and 2nd query results are combined? as you can see in output? with whereHas? if yes how can I combined my raw queries result? any example? – Ali Bhutta Mar 24 '21 at 09:13
  • I also want to know that how can I get company_ids as array from 1st query and pass it to 2nd query ? – Ali Bhutta Mar 24 '21 at 09:15
  • By looping the result with code. – N69S Mar 24 '21 at 09:18
  • any code example? – Ali Bhutta Mar 24 '21 at 09:20
  • you may mention the tables and relations between them, this will help in giving you the raw query to get these data using join. – Abdel-aziz hassan Mar 24 '21 at 10:35
  • Thanks for your precious time, I added relations at the end. – Ali Bhutta Mar 24 '21 at 10:43
  • install https://github.com/barryvdh/laravel-debugbar it will help you to show raw query – Shahrukh Apr 09 '21 at 06:41
  • Why do you need to write that query in RAW sql ? you did not explain that part... Also, you can have better code by using [`when`](https://laravel.com/docs/8.x/queries#conditional-clauses) instead of horrible `if`s and `$jobs = new added query`... – matiaslauriti Apr 14 '21 at 04:42

1 Answers1

1

Regarding how with works, the answer is, the IN() SQL statement. The reason you're able to get away with having Model classes relate to eachother despite theoretically using different connections or DB engines is because Laravel doesn't generate JOIN statements. (I've attempted to make it generate true JOINs based on Model configs in the past, and quickly found out things get tricky when trying to keep table-names aliased to keep them unique, but still be able to reference them in the results).

So, $model->with('relation') will result in something to the effect of:

SELECT * FROM $model::$table;
SELECT * FROM $model->relation()->getTable() WHERE $model->relation()->getKeyName() IN(Model-defined foreign key results from previous query);

As for how to actually see the resulting query, I wrote a debug helper that offers just that: https://gist.github.com/kmuenkel/a6b4e34e5bf6ca44e3c85bf753111850 It's designed to work hand-in-hand with a stack-tract helper, that goes so far as to use Reflection to include field names and default values in the details: https://gist.github.com/kmuenkel/4a1a8a10e0f68a7e3439c4f612523ec7

Once those are wired up, you just call before you execute your queries. Then call it again at any point afterwards, and dump the results:

debug_query();
$model->with(...)->get();
dd(debug_query()->toArray());

This will show you all queries executed between points A and B. If, for example, you place them before and after a function call, with queries run somewhere down-stream, and you want to include a trace details where the queries are called from, you pull in the DebugTrace code as well, and add true as an argument on the point-A function call.

kmuenkel
  • 2,659
  • 1
  • 19
  • 20
  • Nice description – Wahyu Kristianto Apr 12 '21 at 06:33
  • Thanks, Can you share raw query or query builder for above given query?(assuming there is no relation declared in models i.e you're not able to get company by $jobs->with('company'); ) – Ali Bhutta Apr 12 '21 at 11:04
  • I also want to know that how Laravel gives data such that other query has its own tables data saying company:{ all fields(data) of company} -- you can see example above – Ali Bhutta Apr 12 '21 at 11:06