拉拉维尔 如何从多个数据库表中正确选择字段?

  • 本文关键字:选择 字段 数据库 php laravel
  • 更新时间 :
  • 英文 :


我有一个giveaway表,它有一个winner_id列,其中输入了网站上的用户ID。winner_id列中的 ID 必须在users表中查找并显示在站点上找到的用户登录名。如何正确完成此操作?

您正在寻找来自"Giveway"模型端的一对多(反向(关系。首先,您需要创建一个"赠品"模型来表示您的"赠品"数据库表,以防您还没有它。您应该具有"用户"模型,因为默认情况下存在该模型。您的"赠品"模型可能如下所示:

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Giveaway extends Model
{
/**
* Get the user that is related to the giveaway.
*/
public function user()
{
return $this->belongsTo('AppUser', 'id', 'winner_id');
}
}

现在,获取赠品实例,您可以执行以下操作:

// this will print the user instance which is associated to the giveaway row with id #1
dd(Giveaway::find(1)->user);

有关更多详细信息,请查看 Laravel文档:https://laravel.com/docs/6.x/eloquent-relationships#one-to-many-inverse

最新更新