php - Laravel 尝试获取非对象一对一关系的属性

标签 php orm laravel eloquent

用户架构

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/

相关文章:

php 计数函数未在 mysql_fetch_assoc 上显示正确的计数

php - yii phpunit 测试覆盖率 View

php - 带大括号的循环会导致错误的输出

laravel - 以编程方式获取 artisan 命令签名

PHP SimpleXML : How to access nested namespaces?

java - hibernate 中不区分大小写的搜索

Django:尽管实例在查询集中,但 assertIn(instance, queryset) 失败

Java 连接池不限制打开到数据库服务器的 TCP 连接数

php - Laravel 5.4 子查询在什么条件下?

laravel - 如何在 Laravel 中不使用表单的情况下将变量从 View 传递到 Controller ?