【问题标题】:Laravel Relationship Issues - one to oneLaravel 关系问题 - 一对一
【发布时间】:2014-02-17 14:56:36
【问题描述】:

我正在尝试在 Laravel 中构建我的第一个应用程序,但似乎遇到了关系问题。

我有用户和 Staff_Members。一名工作人员与用户帐户相关联,请参阅下面的数据库架构:

staff_members:

Schema::create('staff_members', function($table){
        $table->increments('staff_member_id');
        $table->unsignedInteger('user_id');
        $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        $table->string('first_name');
        $table->string('surname');
        $table->string('image');
        $table->timestamps();
    });

用户:

Schema::create('users', function($table){
        $table->increments('user_id');
        $table->string('username');
        $table->string('password');
        $table->unsignedInteger('type_id')->nullable();
        $table->foreign('type_id')->references('type_id')->on('user_types')->onDelete('set null')->onUpdate('cascade');
        $table->timestamps();
    });

这是我的模型:

用户:

class User extends Eloquent  {

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


public function staff_member(){
    return $this->hasOne('StaffMember', 'user_id');
}



}

员工:

class StaffMember extends Eloquent {
protected $primaryKey = 'staff_member_id';
protected $table = "staff_members";

public function user(){

    return $this->belongsTo('User', 'user_id');
}

}

这是我在我的代码中运行的内容:

$staff = StaffMember::find(1);
$user = User::find(1);
var_dump($staff->user); // Outputs the user correctly
var_dump($user->staff_member); // Outputs NULL

如您所见,员工与用户的关系工作正常并返回用户数据,但用户与员工的关系始终返回 null。我真的看不出我在这里做错了什么并且正在拔头发,非常感谢任何帮助。

更新:

感谢@Gregory,我发现最终的 $user->staff_member 实际上并没有查询数据库,尽管我仍然无法弄清楚为什么会这样或如何解决它?

【问题讨论】:

    标签: php orm laravel laravel-4 eloquent


    【解决方案1】:

    我没有足够的声誉来发表评论,所以我会这样做。 你的代码在我看来不错,你试过打印出 Laravel 使用的 sql 吗?

    $queries = DB::getQueryLog();
    $last_query = end($queries);
    

    这将获取您上次执行的查询,将其打印出来,您可能会更容易看到问题。

    【讨论】:

    • 我在之后添加了 Gregory,但我只得到“select * from users where users.user_id = 1 limit 1”。就好像对链接的查询从未真正执行过
    • 好的,我可以确认 $user->staff_member 实际上并没有查询数据库,到目前为止有 3 个查询,在我调用 $user->staff_member 之后仍然只有 3 个查询。这是否让您对它可能是什么有任何想法?
    • 您是否在终端中执行了 'composer dump-autoload' 只是为了安全,我将尝试重现您的问题
    • 好的,找到了。将函数更改为 public function staffmember(){.. 下划线显然是问题所在。这对我有用,如果它对你有用,请告诉我!
    • 这太棒了,谢谢格雷戈里!我想我是在违背常规,因为现在我查看 laravel 方法,它们通常都是驼峰式的,我只是惊讶于没有以任何方式处理下划线并且没有提供任何反馈 - 我花了几个小时来研究,这让我很恼火,因为我第一次选择使用框架来加速开发。我会将您的答案标记为解决方案 - 非常感谢您的帮助!
    猜你喜欢
    • 2019-11-25
    • 2021-11-15
    • 2018-09-27
    • 2014-08-22
    • 2018-10-03
    • 2013-02-08
    • 2018-05-29
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多