skip to Main Content

When executing the following query:

$jobs = DB::table('jobs')->with('companies:name')->where('published', 0)->get();

I get:

Call to undefined method IlluminateDatabaseQueryBuilder::with().

I want all my jobs where published == 0, with the companies name from a relation. I do not see why with is undefined here, could you guys help me out?

2

Answers


  1. To achieve what you want with IlluminateSupportFacadesDB you can do it like:

    $jobs = DB::table('jobs')
        ->select('jobs.*', 'companies.name')
        ->join('companies', 'jobs.company_id', '=', 'companies.id')
        ->where('jobs.published', 0)
        ->get();
    

    But it’s better to use Laravel Eloquent ORM as it maps your database, instead accessing direct by the query builder.

    Login or Signup to reply.
  2. You cannot use with on Database Query Builder. It can only be used with Eloquent Models. But this will help

    $jobs = DB::table('jobs')
        ->join('companies', 'jobs.company_id', '=', 'companies.id')
        ->select('jobs.*', 'companies.name')
        ->where('jobs.published', 0)
        ->get();
    

    I will suggest you use Eloquent ORM. You will create a model named Job, and another named Company. Then, relate both tables.

    In the Job model class, you will create a relationship with the Company like this

    public function company(){
    
        return $this->belongTo(Company::class);
    
    }
    

    In the Company model class, you will create a relationship with the Job like this

    public function jobs(){
    
        return $this->hasMany(Job::class);
    
    }
    

    I hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search