Laravel 4:如何从belongsTo()关系访问数据?

时间:2014-07-03 12:43:29

标签: php laravel relationships

// models:
class Hometype extends Eloquent {
    public function development() {
        return $this->belongsTo('Development');
    }
}

class Development extends Eloquent {
    public function hometypes() {
        return $this->hasMany('Hometype', 'dev_id');
    }
}

,我可以这样做:

// controller:
$development = Development::where('stuff')->first();
// view:
@foreach ($development->hometypes as $hometype)
    {{ $hometype->stuff }}
@endforeach

非常可爱。

但我似乎无法做到:

// controller:
$hometype = Hometype::where('stuff')->first();
// view:
{{ $hometype->development->stuff }} // <- fails

如何从$ hometype中访问父Development模型中的字段?

我正在诉诸:

'development' => Development::find($hometype->dev_id),

这看起来很傻。

可能重复:Laravel 4 - Can't retrieve data in a one-to-many relationship,但我不是来自...... {/ p>

也类似于:Laravel 4 hasOne / belongsTo relationship(此处没有答案)

2 个答案:

答案 0 :(得分:3)

正如我所看到的,可能存在两个问题:

  1. Hometype中的外键错误(如果您使用的列名不同于“column”_id,则必须指定它)
  2. 您可能正在获取其开发行不存在的Hometype记录

答案 1 :(得分:0)

访问hasMany和belongsTo之间的数据和方法 首先获得所需的模型然后循环

这些是模型:

class ExpenseCategory extends Model
  public function expense_transactions()
  {
      return $this->hasMany('App\ExpenseTransaction');
  }


  class ExpenseTransaction extends Model
      public function expense_category()
      {  
          return $this->belongsTo('App\ExpenseCategory');
      }

以上型号的架构:

Schema::create('expense_transactions', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('expense_category_id')->nullable();
    $table->unsignedInteger('day_sheet_id')->nullable();
    $table->string('expense_title')->nullable();
    $table->unsignedInteger('amount');
    $table->timestamps();

$table->foreign('expense_category_id')
      ->references('id')->on('expense_categories')
      ->onDelete('cascade');

$table->foreign('day_sheet_id')
      ->references('id')->on('day_sheets')
      ->onDelete('cascade');

类别架构:

Schema::create('expense_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();  
    });

仅查找模型

中日期工作表ID的费用交易
$expenseTransactions = ExpenseTransaction::where('day_sheet_id', $id)->get();

显示他们的类别名称 刀片访问: 在foreach循环中

@foreach($expense_transactions as $expense_transaction)
{{ $expense_transaction->expense_category->name  }}