【问题标题】:Get the name of other Users through relationships通过关系获取其他用户的名字
【发布时间】:2017-07-22 19:44:34
【问题描述】:

我有一个模型安排和迁移包括:

Schema::create('arrangements', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('acceptor')->unsigned();
        $table->boolean('confirmed')->default(false);
        $table->timestamps();
});

我可以从如下关系中获取用户名:

$arrangement->user->name

我可以像下面这样获取接受者的 id:

$arrangement->acceptor

但我想获取接受者的名称,如果可能的话我想访问接受者的其他属性

【问题讨论】:

    标签: php laravel eloquent foreign-keys migration


    【解决方案1】:

    改变

    $table->integer('acceptor')->unsigned();
    

    到:

    $table->integer('acceptor_id')->unsigned(); //schema will be more intuitive
    

    在您的Arragement 模型中添加如下关系:

    public function acceptor()
    {
        // I assumed that you acceptor is a reqular user
        return $this->belongsTo(App\User::class, 'acceptor_id');
    }
    

    那么就可以这样访问acceptor了:

    $arragement->acceptor->name;
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2014-11-19
      • 2019-07-24
      相关资源
      最近更新 更多