【发布时间】:2015-04-30 00:40:55
【问题描述】:
我有一个名为 payments 的表,其中包含一个名为 Vendor ZIP 的字段。
我有一个名为201502_postcodes 的表,在这种情况下我的“加入”是该表中的postcode 字段。
如何使用 Eloquent 返回 201502_postcodes 表中的字段值?
我的模特是;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model {
public function postcodeExtract()
{
return $this->belongsTo('App\Models\PostcodeExtract', 'postcode', 'Vendor ZIP');
}
_
<?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 payment()
{
return $this->hasMany('App\Models\Payment', 'Vendor ZIP', 'postcode');
}
所以,我在这个模型上有一个 scope,因为我的表名中的 201502 部分是一个变量(也就是说,每个季度都会出现一个新变量)。
在我的控制器中...我不知道该放什么。我不知道如何让范围和关系都发挥作用。如何编写一个查询,该查询将采用邮政编码/zip 并从(我是否将它们称为“方法”?)邮政编码提取表中输出其中一个字段?
这不是这个问题Laravel 4: Dynamic table names using setTable() 的重复,因为该问题没有涉及或讨论关系。
--- 更新 ---
如果我要使用getTable - 会是这样吗...
class PostcodeExtract {
public function setTableByDate($selected_tablename)
{
$this->table = $selected_tablename;
// Return $this for method chaining
return $this;
}
public function getTable()
{
if (isset($this->table))
$this->setTableByDate($this->table);
return $this->table;
}
}
然后我会在我的控制器中使用它;
$selected_tablename = 201502_postcode //created by some other controller
$postcode_extract = new PostcodeExtract;
$data = $postcode_extract->setTableByDate($selected_tablename)->get()->toArray();
Carbon 的东西并不真正相关。我有一个查找以获取这些表名,事实是带有日期值的前缀不应该意味着它被视为日期。
【问题讨论】:
-
@user3158900 不是。