在Laravel 6中从外键获取数据

时间:2019-12-30 22:54:17

标签: php database laravel foreign-keys laravel-6

我想做的是使用表中的外键从表中获取一行,该行链接到另一个表,然后在视图中显示该行的特定列。

在某些情况下,这是一个有关体育赛事的网站。在视图内部,用户应该能够看到clicked事件的详细信息。这些细节中应该包含运动类别和运动。但是,在Laravel 6.5中,我找不到方法。


我所拥有的:

数据库表:

sport_categories (id, name)
sports (id, sport_category_id, name)
events (id, title, sport_category_id, sport_id)

EventsController

public function show(Event $event) 
{
    return view('events.show', ['event' => $event]);
}

查看

<div id="event-sport-category">
   <span>Sport Category:</span>
   <span id="show-event-sport-category-label">{{$event->sport_category_id}}</span>
</div>
<div id="event-sport">
   <span>Sport:</span>
   <span id="show-event-sport-label">{{$event->sport_id}}</span>
</div>

运动类别模型(空)

class SportCategory extends Model
{
    //
}

运动模型

class Sport extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

事件模型

class Event extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

当然,这时返回视图的只是events表的id列。如何返回每个ID对应的name

1 个答案:

答案 0 :(得分:2)

根据您的数据库设置:

  
      
  • sport_categories(ID,名称)
  •   
  • 体育(id,sport_category_id,姓名)
  •   
  • 事件(id,标题,sport_category_id,sport_id)
  •   

所以..在此响应中,我假设:

  • 一个Category有许多Sport
  • 一个Sport有许多Event

注意::鉴于Sport已经属于Category,因此您无需在{{ 1}}表:相关的category_sport_id行应该已经有了它。

现在,您的问题。

  

如何返回每个ID的对应名称?

定义Relationships

在您的events模型中:

sport

您的Category.php模型:

class SportCategory extends Model
{

    protected $guarded = []; // <---

    // ...

    public function sports() // <---
    {
        return $this->hasMany(Sport::class);
    }
}

在您的Sport.php模型中:

class Sport extends Model
{

    protected $guarded = []; // <---

    // ...

    public function events() // <---
    {
        return $this->hasMany(Event::class);
    }

    public function category() // <---
    {
        return $this->belongsTo(SportCategory::class);
    }
}

通知:我在每个模型中添加了一个Event.php,这告诉Laravel在将其返回到视图时包括所有字段。 Read this

现在已经定义了关系,您需要在将变量返回到视图之前加载关系。当然,您可以在视图本身中加载关系,但是为了优化查询,您可以像这样should eager加载该对象(在这种情况下,由于需要使用模型绑定来解析对象,因此需要进行延迟加载):

class Event extends Model
{

    protected $guarded = []; // <---

    // ...

    public function sport() // <---
    {
        return $this->belongsTo(Sport::class);
    }
}

现在,您应该在$ event变量protected $guarded = [];和嵌套的public function show(Event $event) { $event->load('sport.category'); // <--- return view('events.show', ['event' => $event]); } 中包含此记录,以便只在视图中输出它们:

$event->sport