gpt4 book ai didi

Laravel, Eloquent n :m relationship

转载 作者:行者123 更新时间:2023-12-04 02:19:45 24 4
gpt4 key购买 nike

我尝试使用 Eloquent 在 Laravel 中定义一个 n:m 关系。我给出了下表:

用户:

  • 身份证

东西

  • 身份证

用户事物

  • 事物编号

在我的 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');
}

当我调用 Controller 时

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

我收到以下消息:

Object of class Illuminate\Database\Eloquent\Relations\HasMany couldnot be converted to string.

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

最佳答案

你可以试试这个(对多对多关系使用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()

关于Laravel, Eloquent n :m relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31483986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com