猿问

如何使用 eloquent 从数据库中检索 created_at 数据

我如何在 laravel 中用 eloquent 从数据库中检索 created_data?,我使用的是属于多个关系,我想显示借书数据和借阅日期,我已成功显示借书数据,但我无法获取 created_at 数据来自数据库中另一个名为 borrow_history 的表


书本.php


public function borrowed()

{

    return $this->belongsToMany(User::class, 'borrow_history')

    ->withTimestamps();

}

用户.php


public function borrow(){

    return $this->belongsToMany(Book::class, 'borrow_history')

    ->withTimestamps();

}

这是我当前的 HomeController.php 索引


public function index()

{

    $books = auth()->user()->borrow;

    return view('home', [

        'books' => $books,

    ]);

}

我想在 home.blade.php 显示 created_at 数据


@foreach($borrow_history as $borrow)

   <p>

      <i class="material-icons">date_range</i> Borrow_date : {{ ???? }}

   </p>

@endforeach

谁能帮我?


婷婷同学_
浏览 105回答 1
1回答

白板的微信

当您belongsToMany使用 Laravel 加载(多对多)关系时,它将在该关系上包含一个枢轴属性。由于您有withTimestamps()关系,它将包括created_atandupdated_at值。您应该能够通过以下方式实现您所追求的目标:$borrow->pivot->created_at;有关更多信息,您可以参考文档(向下滚动到检索中间表列)
随时随地看视频慕课网APP
我要回答