用户架构
public function up()
{
Schema::table('users', function($table)
{
$table->create();
$table->increments('id');
$table->string('email');
$table->string('real_name');
$table->string('password');
$table->timestamps();
});
}
Dni 架构
public function up()
{
Schema::table('dnis', function($table){
$table->create();
$table->increments('id');
$table->integer('user_id');
$table->string('numero',15);
$table->timestamps();
});
}
我有这些模型
User:
<?php
class User extends Eloquent
{
public function setPassword($string)
{
$this->setAttribute('password', Hash::make($string));
}
public function dni()
{
return $this->hasOne('Dni', 'user_id');
}
}
Dni
<?php
class Dni extends Eloquent
{
public function user()
{
return $this->belongsTo('User');
}
}
当我尝试
public function getIndex()
{
$users = User::all();
return View::make('users.index') -> with('users', $users);
}
我在 View 中使用了 foreach 并且无法让 {{ $user->dni->numero }}
工作
我想我在 getIndex()
中遗漏了一些东西,但无法弄清楚是什么。
我在foreach中使用了var_dump($users)
和var_dump($user)
,我似乎没有在$users上发送dni日期
最佳答案
首先,您并不急于加载此内容。每次迭代 $users 时,您都会进行数据库查询以获取每个用户的 Dni 模型。将变量传递到您的 View ,如下所示:
$users = User::with('dni')->get();
您遇到的问题可能是您没有每个单独用户的 Dni 对象,在这种情况下您可以使用以下方式获取用户:
$users = User::has('Dni')->with('dni')->get();
解决方案:
看起来 Laravel 不喜欢 User1.php 中重复的类名,并且正在调用该用户模型而不是您的替代模型。您可以删除 User1.php 并运行 composer dump-autoload
或更改 User1.php 中的类名称并运行 composer dump-autoload
。
关于php - Laravel 尝试获取非对象一对一关系的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971698/