php - Laravel Eloquent:我的数据透视表有关系
问题描述
这里有一些关于表的信息
User table
-id
-name
UserProduct table
-id
-user_id
-product_id
Product table
-id
-name
Contribution
-id
-user_product_id
-contribution
用户模型
public function products()
{
return $this->belongsToMany('App\Product');
}
产品型号
public function users()
{
return $this->belongsToMany('App\User');
}
用户产品枢轴模型
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserProduct extends Pivot
{
public function contribution()
{
return $this->hasMany('App\Contribution');
}
}
我尝试喜欢auth()->user()->products()->first()->pivot->contribution()
,但它给出了一些错误。
调用未定义的方法 Illuminate\Database\Eloquent\Relations\Pivot::contribution()
解决方案
你可以使用自定义数据透视表模型吗?
class UserProduct extends Pivot
{
public function contribution()
{
return $this->belongsTo('App\Contribution');
}
}
// User model
public function products()
{
return $this->belongsToMany('App\Product')->using('App\UserProduct');
}
希望它可以帮助你。
推荐阅读
- windows - Reactjs:为页面构建静态 html 失败
- .net-core - 智能感知和 .NetCore
- apache-spark - 如何通过 PySpark 查找 Hive 表是否定义为外部表?
- java - vert.x - 可能有多少个 Timer
- php - Preg 匹配仅验证带符号 + 或 - 的整数或小数
- python - 将 tf.nn.embedding_lookup 与多列一起使用
- python - 无法使用 scrapy 从雅虎财经网站获取当前股价
- java - Java 中的 TeamSpeak 3 MusicBot
- php - 如何正确处理数组?
- moq - 使用 Autofac 和 Moq 在服务库中模拟代理工厂