【问题标题】:Laravel model: instance or relationship?Laravel 模型:实例还是关系?
【发布时间】:2017-02-10 07:31:11
【问题描述】:

我不是专业的程序员,所以我不知道我描述得很好。

在模型中建立Eloquent关系,使用... - >belongsTo..等语法和函数。

这些模型的背后是我数据库中的表。

在我的 (laravel) 应用程序中,我有一个登录用户,他需要有关其他用户的某些信息。归根结底,他们都只是用户,坚持在用户的表中。

因此,当我使用与另一个对象(例如汽车)的关系时,一切都很好。当我尝试使用与另一个用户的关系时,我会收到 Cannot redeclare class App\Models\User.

之类的错误

我想我在这里误解了一些东西。

我觉得也许我应该“实例化”另一个版本的用户(作为“经理”)......但我真的需要吗?它更像是一种查找,而不是其他任何东西。我不确定我什至会知道该怎么做。

请指点一下?

【问题讨论】:

  • 你能提供一些代码吗?显然你有多个用户类声明

标签: laravel-5.2


【解决方案1】:

听起来您创建了两个不同的“用户”模型:

// /app/User.php:

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    // ...
    public function user() {
        return $this->hasOne('App\Models\User');
    }
}


// /app/models/User.php:

<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    // ...
    public function user() {
        return $this->belongsTo('App\User');
    }
}

相反,您希望拥有一个属于自己的类:

// /app/User.php:

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    // ...
    public function parent() {
        return $this->belongsTo('App\User');
    }

    public function children() {
        return $this->hasMany('App\User');
    }
}

然后在您的数据库中确保 users 表具有 user_id 属性(编辑 database/migrations/2014_10_12_000000_create_users_table.php):

$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');

现在您可以将用户彼此关联:

<?php

$manager = new User();
$employeeOne = new User();
$employeeTwo = new User();

$manager->children()->saveMany([
    $employeeOne,
    $employeeTwo
]);

dd( $employeeTwo->parent->name ); // Manager's name

【讨论】:

    猜你喜欢
    • 2017-09-17
    • 2019-11-27
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2020-04-02
    • 2018-07-11
    相关资源
    最近更新 更多