Laravel,Eloquent n:m关系

3

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

用户:

  • ID
  • foo

物品:

  • ID

用户-物品:

  • thing_id
  • foo

在我的“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类的对象转换为字符串。 ```
我的问题是,我不能在组合表中使用用户ID作为外键。它必须是foo列。

错误似乎与关系无关。在您的代码中,某个对象被转换为字符串。请查看错误消息,应该会显示出发生错误的文件名和行号。请粘贴代码的这部分内容。 - jedrzej.kurylo
当你使用return dd($things)时会发生什么?$user->things()返回一个集合实例。尝试使用动态属性,看看是否有效:$things = $user->things;或者$things = $user->things->first(); - CrackingTheCode
1个回答

4
您可以尝试使用belongsToMany来处理多对多关系。
// 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接