如何从MySQL的另一个表中检索数据,而从列从第一个表的数据?



在我开始之前,我使用Laravel 8 &PHP 7.4.29。
我想要达到的效果是,您可以根据第一个表(视频)的列从另一个表(用户)中获得用户名。

让我们仔细看看第一张表。它包含title,description,uploader(值为用户的UUID)等列。我所面临的问题是,我实际上无法检索我想要的用户名。而不是,我得到这样的错误:

Trying to get property 'username' of non-object

,代码是:

(代码写得很好,但是Stack Overflow语法高亮显示坏了,我猜)

<?php
$videos = DB::select("select * from videos where title like concat(?) or description like concat(?) and public = ?", ["%".$_GET['query']."%", "%".$_GET['query']."%", 2]);
foreach ($videos as $video) {
$users = DB::select("select * from users where uuid = ?", [$video->uploader]);
?>
<div class="video">
<a href="/video?id={{{ $video->videoid }}}">
<div class="row">
<div class="col-12 col-md-3">
<div class="thumbnail">
<!-- the value below is a placeholder so far -->
<span class="duration-mark">4:51</span>
</div>
</div>
<div class="col-12 col-md-9 my-2 my-md-0">
<h4 class="mb-1">{{{ $video->title }}}</h4>
<p class="viddesc mb-2">{{{ $users->username }}} ● {{{ date('Y/m/d', strtotime($video->uploaddate)); }}}</p>
<p class="viddesc">{{{ $video->description }}}</p>
</div>
</div>
</a>
</div>
<?php
}
?>

将值赋给一个新变量也不能工作。

我已经浏览堆栈溢出前一段时间,并找到了解决方案,我应该检索数据从两个表在一个SQL请求(在我的情况下-select * from videos, users)。它以某种方式工作,但不是预期的结果(我有1个视频信息在第一个表&2个用户在第二个表中),结果是重复的。

我实际上有一些PHP和Laravel的经验,但我不记得这是怎么做到的(我已经从PHP编程中休息了相当大的一段时间)。如果有任何解决办法,我都欢迎。

提前感谢!

Use Joins

在你的情况下,使用左连接,如果你有视频没有匹配的上传器,如果你需要所有的视频。

也可以使用内连接,如果你想获得视频,只有匹配的上传者存在于表中。

select videos.*,users.* from videos LEFT JOIN users ON users.uuid = videos.uploader where title like concat(?) or description like concat(?) and public = ?", ["%".$_GET['query']."%", "%".$_GET['query']."%", 2] 

参考:https://www.w3schools.com/sql/sql_join_left.asp

注意:如果你在两个表中有一个公共列,那么视频记录的值将被用户列值

覆盖示例:videos [id,name,uploader,addedAt]Users [uid, name]

in this case the result will be 

videos.id,videos,uploader,videos.addeAt,users.uuid,users.name
* The videos.name column willbe overrided by users.name

要解决这个问题,可以使用上面的查询,如

(例子)

select videos.*,users.*,videos.name as "videoname" from videos LEFT JOIN users ON users.uuid = videos.uploader where title like concat(?) or description like concat(?) and public = ?", ["%".$_GET['query']."%", "%".$_GET['query']."%", 2] 

这不是在laravel上从视图访问模型的好方法。你应该在控制器中做。但是,对于多个数据应该使用get()方法,对于单个数据应该使用fist()方法来获取实际的数据对象。你的代码应该看起来像

<?php
$videos = DB::select("select * from videos where title like concat(?) or description like concat(?) and public = ?", ["%".$_GET['query']."%", "%".$_GET['query']."%", 2])->get();
foreach ($videos as $video) {
$users = DB::select("select * from users where uuid = ?", [$video->uploader])->first();

?比;

相关内容

最新更新