【问题标题】:How to joins table in Laravel 5.2?如何在 Laravel 5.2 中加入表格?
【发布时间】:2016-05-16 15:27:43
【问题描述】:

我是 Laravel 框架的初学者。我已经搜索了我的问题并得到了一些解决方案,但这些都没有解决我的问题。所以,

个人资料表: 当任何用户创建配置文件时,我都需要填写userID 列。为此,我正在尝试编写如下代码:

轮廓模型:

    public function users(){
        return $this->belongsTo('App\User','userID');
   }

和用户模型:

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

这样,它每次都保持null 的价值。我该如何解决这个问题? 提前致谢。

【问题讨论】:

标签: php mysql laravel eloquent laravel-5.2


【解决方案1】:

所以假设你有以下(你会做的)

public function profiles()
{
  return $this->belongsTo(\App\User::class); // we do not need to provide the user_id because laravel assume we are using that
}

<?php
// Profile.php (Model)

public function user()
{
  $this->belongsTo(\App\User::class); // Again we do not need to provide the information because of the table / column names we are using
}

您有几个选项,您可以在创建配置文件时分配 user_id(只要它在可填写的字段中。

$profile = new Profile;
$profile->user_id = \Auth::getId(); // current logged in user
$profile->somethingElse = 'abc';
$profile->save();

或者既然我们有关系,你应该可以做这样的事情

$profile = new Profile;
$profile->somethingElse = 'abc';
// We will use the current logged in user again
Auth::user()->profiles()->save($profile); // will automagically fill in the user_id with the logged in user's id.

希望能有所启发

【讨论】:

  • 两者都给我错误...第一个给我“call_user_func_array() 期望参数 1 是有效回调,类 'Illuminate\Auth\SessionGuard' 没有方法 'getId'”和第二个“”调用未定义的方法 Illuminate\Database\Query\Builder::save()
  • 你确定这两个函数是属于彼此的吗?
  • 如果需要,您可以将它们更改为 hasOne... 如果关系不起作用,您可以使用第一个建议,因为调用 save() 来分配“user_id”
【解决方案2】:

在向Profile Table插入数据时,您只需要执行以下操作:

$profile = new Profile();
$profile->userID = Auth::user()->id;
$profile->other_columns = 'values'
.....
$profile->save();

此处无需加入表格以在 Profile Table 中插入值。希望对你有帮助

【讨论】:

  • 现在我明白了。接受。
  • 太棒了 :) 很高兴它对你有所帮助
猜你喜欢
  • 2016-10-20
  • 2021-06-14
  • 1970-01-01
  • 2013-10-12
  • 2019-11-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多