难以捉摸的关系


Eloquent Relationship

为什么我在这样一个简单的关系查询中遇到这个错误?

Call to undefined method Illuminate'Database'Query'Builder::country()

我只想从名为pc_country的查找表中获得一个查找值列表。我甚至包含了名称空间!

控制器;

$tableName = $postcode_tablename->dataset; //eg 201502_postcode
$country = PostcodeExtract::fromTable($tableName)
                        ->country() //this is generating the error!
                        ->distinct()
                        ->select('description')
                        ->get();
var_dump($country);
exit;

国家模式;

<?php namespace App'Models;
use Illuminate'Database'Eloquent'Model;
class Country extends Model {
  protected $connection = 'postcodes';
  public $table = 'pc_country';
  protected $fillable = ['description', 'country_id', 'code'];
  public function postcodeExtract()
  {
    return $this->hasMany('App'Models'PostcodeExtract');
  }
}

邮政编码提取模型;

<?php namespace App'Models;
use Illuminate'Database'Eloquent'Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
protected $fillable = ['country'];
  public function scopeFromTable($query, $tableName) 
  {
    return $query->from($tableName);
  }
  public function country()
  {
    return $this->belongsTo('App'Model'Country');
  }
}

我的201502_postcode表有一个country_idpc_country表有一个子字段id,它可以在上面进行查找。对吗?我看不出有什么问题。。。

您使用了fromTable方法(scope),它返回了雄辩的查询生成器,因此您的关系不可用。在不调用该方法的情况下考虑相同的代码。

如果您想更改模型的表,请创建一个实例,然后在创建的实例上调用setTable方法,然后使用您的实例查询

$instance = new PostCodeExtract();
$instance->setTable ("table");
$country = $instance->country()->........

很抱歉,我在手机上无法提供好的示例代码,但你可以用这种方法实现