在同一查询中使用范围和关系

I am having a really hard time trying to use the Scope and the Relationship elements of Eloquent within the same query.

My 201502_postcode table has a column gor which has a foreign key lookup in the pc_gor_030315 table. I ultimately want to return/display the description column within pc_gor_030315 table.

I am using Scope, because my table names are likely to change. Don't worry about that here. I already have the code to do that. For simplicity I have called the tables 201502_postcode and pc_gor_030315.

At the moment I am getting the following error;

Call to undefined method Illuminate\Database\Query\Builder::lookupTable()

Here is my controller;

$list = PostcodeExtract::fromTable('201502_postcode')
                        ->lookupTable('pc_gor_030315')
                        ->distinct()
                        ->select('description')
                        ->get();

var_dump($list);

Here is my PostcodeExtract model;

<?php namespace App\Models;
  use Illuminate\Database\Eloquent\Model;

   class PostcodeExtract extends Model {

   protected $connection = 'postcodes';

    public function scopeFromTable($query, $tableName) 
    {
     return $query->from($tableName);
    }

    public function gorLookup()
    {
     //'oldcode' is the local key
     return $this->belongsTo('App\Model\GorLookup', 'oldcode'); 
    }
  }

And here is my GorLookup;

<?php namespace App\Models;

  use Illuminate\Database\Eloquent\Model;

  class GorLookup extends Model {

    protected $connection = 'postcodes';

    protected $fillable = array('description', 'oldcode');

    public function postcodeExtract()
    {
      return $this->hasMany('App\Models\PostcodeExtract', 'oldcode');
    }

    public function scopeLookupTable($query, $lookupTable) 
    {
      return $query->join($lookupTable);
     }  
  }

Let's take a look at your first scope.

fromTable scope is found in Eloquent Class PostcodeExtract.

Therefore, PostcodeExtract::fromTable('201502_postcode') works perfectly.

As for your second scope lookupTable, it is found in Eloquent Class GorLookup.

Therefore, it should be called with GorLookup::lookupTable.

However, in your code, you are chaining the scope lookupTable on an object of class PostcodeExtract, so it definitely won't work.

Solution:

Place the lookupTable scope in the PostcodeExtract class itself.