gpt4 book ai didi

php - Laravel 中的表连接

转载 作者:行者123 更新时间:2023-11-30 23:01:45 25 4
gpt4 key购买 nike

数据库结构

用户

id | name
---+---------
1 | OP
2 | noob

项目

id | name | user_id
---+------+--------
1 | car | 1
2 | bus | 2
3 | box | 1

评论

id | user_id | item_id | comment
---+---------+---------+---------------
1 | 1 | 3 | this is a box.

应用

app/routes.php

View::share('top_comments', User::join('comments', 'users.id', '=', 'comments.user_id')
->take(3)
->get()
);

app/views/test.php

@foreach ($top_comments as $comment)
username: {{ $comment->name }}<br />
comment: {{ $comment->comment }}<br />
item id: {{ $comment->item_id }}
@endforeach

电流输出

username: OP
comment: this is a box
item id: 3

期望的输出

username: OP
comment: this is a box
item id: 3
item name: box

我希望能够调整我的 top_comments 查询以包含 items.name。当前 {{ $comment->name }} 返回用户名。我认为具有相同的字段名称会导致冲突...建议?

最佳答案

你可以使用这个:

User::join('comments', 'users.id', '=', 'comments.user_id')
->join('items', 'users.id', '=', 'items.user_id')
->get(array('users.*', 'comments.*', 'items.user_id', 'items.name as itemname'));

View 中:

@foreach ($top_comments as $comment)
...
item name: {{ $comment->itemname }}
@endforeach

关于php - Laravel 中的表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23699793/

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