2015-07-25 1 views
2

У меня есть три таблицы (экземпляры, пользователи, user_instance). Каждому пользователю может быть присвоен один экземпляр. У экземпляра может быть много разных пользователей.Проблема с сопоставлением отношений Laravel Eloquent с тремя таблицами и функцией belongsTo()

Я пытаюсь получить экземпляр instance_id из экземпляра, которому назначен конкретный пользователь, используя функцию Laravel 5.1 Eloquent и belongsTo(), вызывая $ this-> user-> instance-> instance_id.

Независимо от того, что я пытался, я всегда получаю результат NULL в моем AuthController.php:

DB Schema:

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/Контроллеры/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/Модели/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/Модели/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/модели/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'); 
     } 
    } 
    ?> 
+0

В модели пользователя вы имеете ' instance() ', тогда как в AuthController вы вызываете' instance', т.е. без 's'. Можете ли вы проверить его опечатку или что ..? – hhsadiq

+0

спасибо, я обновил это в описании. к сожалению, это не решает проблему. –

+0

'die ($ this-> user-> instance-> instance_id);' в этом коде '$ this-> user' вернет вам объект' User'. И затем вы хотите, чтобы эти пользователи использовали «Экземпляр». Я хочу сказать, что ваша модель 'User' не имеет никакого метода' instance'. – hhsadiq

ответ

1
public function instance() 
{ 
return $this->belongsTo('App\Models\User_Instance'); 
} 

belongsTo, в вышеуказанном способе, в частности, примените условие where, используя snakecase (i .e. instance_id) .. но в вашем случае это приведет к неправильному результату или вообще не приведет к результату (вы хотите сопоставить на user_id)

Как предлагает Laravel - Racquent. если внешний ключ в родительской модели не snakecase имени (instance_id), вы можете передать пользовательское имя ключа в качестве второго аргумента метода belongsTo:

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

>>laravel relations

+0

Большое спасибо за подсказку! –

Смежные вопросы