【问题标题】:Laravel, Eloquent n:m relationshipLaravel,雄辩的 n:m 关系
【发布时间】:2015-10-07 15:45:36
【问题描述】:

我尝试使用 Eloquent 在 Laravel 中定义一个 n:m 关系。我有以下表格:

用户:

  • 身份证

事情

  • 身份证

users_things

  • thing_id

在我的User 模型中,我定义了以下关系

public function things() {
  return $this->hasMany('App\Thing', 'user_things', 'foo', 'thing_id');
}

Things模型中是对应的

public function users() {
  return $this->hasMany('App\User', 'user_things', 'thing_id', 'foo');
}

当我调用控制器时

$user = User::find(1) //works
//$thing = Thing::find(1) works
$things = $user->things();
return $things

我收到以下消息:

类 Illuminate\Database\Eloquent\Relations\HasMany 的对象可以 不转换为字符串。

我的问题是,我不能使用 User ID 作为组合表中的外键。它必须是foo 列。

【问题讨论】:

  • 该错误似乎与关系无关。在您的代码中的某处,一个对象被转换为一个字符串。看一下错误信息,应该有错误发生的文件名和行号。请粘贴这部分代码。
  • 当你 return dd($things)? $user->things()` 返回一个 Collection 实例时会发生什么。改用动态属性,看看是否有效:$things = $user->things;$things = $user->things->first();

标签: laravel foreign-keys eloquent laravel-5


【解决方案1】:

您可以试试这个(使用belongsToMany 表示many-to-many 关系):

// User.php

protected $primaryKey = 'foo';
public $incrementing = false;

public function things() {
    return $this->belongsToMany('App\Thing', 'user_things', 'foo', 'thing_id');
}

// Thing.php
public function users() {
    return $this->belongsToMany('App\User', 'user_things', 'thing_id', 'foo');
}

最后,使用$user->things 代替$user->things()

【讨论】:

    猜你喜欢
    • 2015-03-14
    • 2018-11-28
    • 2015-01-11
    • 2021-06-03
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多