【问题标题】:Laravel Eloquent relationship mapping issue with three tables and belongsTo() functionLaravel Eloquent 关系映射问题与三个表和 belongsTo() 函数
【发布时间】:2015-10-16 00:17:32
【问题描述】:

我有三个表(instances、users、user_instance)。每个用户都可以分配给一个实例。一个实例可以有许多不同的用户。

我尝试使用 Laravel 5.1 Eloquent 和 belongsTo() 函数,通过调用 $this->user->instance->instance_id 从分配给特定用户的实例中获取 instance_id。

无论我尝试了什么,我的 AuthController.php 中总是得到 NULL 结果:

数据库架构:

    mysql> show columns from instances;
    +------------+------------------+------+-----+---------+----------------+
    | Field      | Type             | Null | Key | Default | Extra          |
    +------------+------------------+------+-----+---------+----------------+
    | id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | name       | varchar(150)     | NO   |     | NULL    |                |
    | key        | varchar(150)     | NO   |     | NULL    |                |
    | created_at | int(11)          | NO   |     | NULL    |                |
    | updated_at | int(11)          | NO   |     | NULL    |                |
    +------------+------------------+------+-----+---------+----------------+

    mysql> show columns from users;
    +----------------+---------------------+------+-----+---------+----------------+
    | Field          | Type                | Null | Key | Default | Extra          |
    +----------------+---------------------+------+-----+---------+----------------+
    | id             | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
    | first_name     | varchar(50)         | YES  |     | NULL    |                |
    | last_name      | varchar(50)         | YES  |     | NULL    |                |
    | email          | varchar(100)        | NO   |     | NULL    |                |
    | password       | varchar(255)        | NO   |     | NULL    |                |
    | salt           | varchar(255)        | YES  |     | NULL    |                |
    | remember_token | varchar(255)        | YES  |     | NULL    |                |
    | created_at     | int(10) unsigned    | NO   |     | NULL    |                |
    | updated_at     | int(10)             | NO   |     | NULL    |                |
    | last_login     | int(10) unsigned    | YES  |     | NULL    |                |
    | ip_address     | varchar(15)         | NO   |     | NULL    |                |
    | timezone       | int(10)             | YES  |     | NULL    |                |
    | active         | tinyint(1) unsigned | YES  |     | NULL    |                |
    +----------------+---------------------+------+-----+---------+----------------+

    mysql> show columns from user_instance;
    +-------------+------------------+------+-----+---------+----------------+
    | Field       | Type             | Null | Key | Default | Extra          |
    +-------------+------------------+------+-----+---------+----------------+
    | id          | int(10) unsigned | YES  | PRI | NULL    | auto_increment |
    | user_id     | int(10) unsigned | NO   |     | NULL    |                |
    | instance_id | int(10) unsigned | NO   |     | NULL    |                |
    | created_at  | int(11)          | NO   |     | NULL    |                |
    | updated_at  | int(11)          | NO   |     | NULL    |                |
    +-------------+------------------+------+-----+---------+----------------+

App/Controllers/AuthController.php

    <?php
    use App\Models\User;
    use App\Models\Instance;
    use App\Models\User_Instance;
    class AuthController extends Controller {
    ...
    die($this->user->instance); // Returns: NULL
    ...
    }
    ?>

App/Models/Instance.php

    <?php namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class Instance extends Model
    {
        /**
         * Indicates if the model should be timestamped.
         *
         * @var bool
         */
        public $timestamps = true;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'instances';

        /**
         * The tables primary key.
         *
         * @var string
         */
        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = ['name', 'key', 'created_at', 'updated_at'];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = [];
    }
    ?>

App/Models/User_Instance.php

    <?php namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class User_Instance extends Model
    {
        /**
         * Indicates if the model should be timestamped.
         *
         * @var bool
         */
        public $timestamps = true;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'user_instance';

        /**
         * The tables primary key.
         *
         * @var string
         */
        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = ['user_id', 'instance_id', 'created_at', 'updated_at'];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = [];
    }
    ?>

App/Models/User.php

    <?php namespace App\Models;

    use Illuminate\Auth\Authenticatable;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Auth\Passwords\CanResetPassword;
    use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
    use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
    use Zizaco\Entrust\Traits\EntrustUserTrait;

    class User extends Model implements AuthenticatableContract, CanResetPasswordContract
    {
        use Authenticatable, CanResetPassword, EntrustUserTrait;

        /**
         * Indicates if the model should be timestamped.
         *
         * @var bool
         */
        public $timestamps = true;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'users';

        /**
         * The tables primary key.
         *
         * @var string
         */
        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'first_name',
            'last_name',
            'email',
            'password',
            'salt',
            'remember_token',
            'created_at',
            'updated_at',
            'last_login',
            'ip_address',
            'timezone',
            'active'
            ];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = ['password', 'remember_token'];

        /**
         * Map the instance with the user.
         *
         * @var int
         */
        public function instance()
        {
            return $this->belongsTo('App\Models\User_Instance');
        }
    }
    ?>

【问题讨论】:

  • 在用户模型中你有instances() 函数,而在AuthController 中你调用instance 即没有's'。你能检查一下是错字还是什么..?
  • 谢谢,我已经在描述中更新了。不幸的是,这并不能解决问题。
  • die($this-&gt;user-&gt;instance-&gt;instance_id); 在此代码中$this-&gt;user 将返回User 的对象。然后你想让这个用户相关Instance。我的观点是您的 User 模型没有定义任何 instance 方法。
  • 谢谢。我注意到 die(var_dump($this->user)) 不包含与“实例”相关的任何内容 - 这是正常行为吗?
  • 你能告诉我什么 var_dump($this->user) 返回..?

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:
public function instance()
{
 return $this->belongsTo('App\Models\User_Instance');
}

belongsTo ,在上述方法中,具体应用 where 条件使用snakecase(即instance_id)..但在你的情况下,这会导致错误的结果或根本没有结果(你想映射到user_id)

正如 Laravel-Eloquent 所建议的那样。 如果父模型上的外键不是蛇形名称(instance_id),您可以将自定义键名称作为第二个参数传递给 belongsTo 方法:

return $this->belongsTo('App\Models\User_Instance','user_id');

>>laravel relations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 2015-12-22
    • 2016-07-21
    • 1970-01-01
    • 2020-12-19
    • 2016-03-17
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多