laravel - Laravel - Eloquent 如何建立这种关系 HasMany -> BelongToThrough
问题描述
我怎么能想出这种关系呢?
User:
- id
- name
- username
Post
- id
- user_id
- comment_id
Coment
- id
- other_id
Other
- id
- name
- descripton
所以关系应该是:
User - belongsToMany -> Post - belongsTo -> Comment - belongsTo -> Other
在这个关系中,user
有很多职位,但comment_id
关系是属于的。我不能使用 hasManyThrough 因为关系不同。
有没有办法使这项工作?它应该是 hasMany -> BelongsToThrough
我可以使用 hasMany 然后在每个项目上调用 BelongsTo,但我的关系太深了。
它需要一个可以使用 hasMany 然后 belongsToThrough 这样的关系的关系
更新
有一个belongsToMany而不是hasMany,但仍然不确定我是否可以解决这个问题
有替代解决方案
class User {
public function user_post_comments () {
return $this->belongsToMany(Post::class);
}
public function getCommentsAttribute() {
return $this->user_post_comments->map(function ($value, $key) {
$obj = $value->comment;
$obj->pivot=(object) [
// Extra variable for the nested
];
return $obj;
});
}
}
class Post {
public function comment () {
return $this->belongsTo(Comment::class);
}
}
$this->user->comments
将返回帖子评论而不是帖子
解决方案
https://laravel.com/docs/8.x/eloquent-relationships#has-many-through
您可以像这样从用户那里获得评论
class User extends Model
{
/**
* Get all of the Comments for the Post.
*/
public function comments()
{
return $this->hasManyThrough(Comment::class, Post::class);
}
/**
* Get all of the Post.
*/
public function posts()
{
return $this->hasMany(Post::class);
}
}
像这样获取其他人的评论
class Comment extends Model
{
public function others()
{
return $this->belongsTo(Other::class);
}
}
并得到这样的最终数据
$data = User::with(['comments.others'])->get();
推荐阅读
- c - make—我可以抑制格式截断错误吗?
- json.net - 自定义 Newtonsoft.Json 反序列化验证行为
- c - 与 Stellaris tivaC 启动板 TM4C123 的 LCD 接口
- reactjs - 从 Firebase 获取数据不使用 React JS 显示?
- ios - Stripe ios paymentContext 和 paymentMethodViewController 有什么区别
- python - 如何在 XPath 中选择第二个 div 元素?
- ruby-on-rails - 使用rspec时如何打印当前页面响应
- assembly - 了解汇编基本代码
- javascript - 有没有相当于.Contains of c#的js
- mysql - 如何使用 python 与 MySQL 服务器上的其他客户端连接进行通信?