【问题标题】:Display created_at from pivot table in Laravel 4在 Laravel 4 中显示数据透视表中的 created_at
【发布时间】:2014-11-17 20:05:47
【问题描述】:

我有三个表 - 与会者、消息和与会者消息。当向用户发送标准化消息时,一条记录将添加到数据透视表attendee_message,其中包含与会者的id、消息的id 和created_at 字段中的日期/时间戳。

我的问题是参加者和消息表都有一个名为 created_at 的字段,当我去显示发送消息的日期/时间(来自参加者消息列的 created_at)时,它显示来自消息表的 created_at。如何改为显示 attentee_message 表中的 created_at?

从模型中获取参加者、范围和关系的函数:

    public function getatts() {
        $atts = Attendee::cmo()->orderBy('created_at');
        $atts = $atts->paginate(25);
        return $atts;
    }

    public function scopeCmo($query)
    {
        return $query->where('block_id', '=', 3);
    }

    public function messages() {
        return $this->belongsToMany('\App\Models\Message','attendee_message','attendee_id','message_id')
            ->withPivot('id');
    }

来自我的 list.blade.php:

@foreach ($att->messages as $message)
    <li>'{{$message->subject}}' sent {{$message->created_at}}</li>
@endforeach

【问题讨论】:

    标签: mysql laravel laravel-4 eloquent


    【解决方案1】:

    要访问数据透视表中的行,您可以使用pivot 属性。 Laravel docs

    $message->pivot->created_at
    

    但是,默认情况下,pivot 对象中只有键。所以你需要这样做

    ->withPivot('created_at');
    

    关于关系。在你的情况下,如果你也想在里面有id,那就是-&gt;withPivot('id', 'created_at')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 2015-08-06
      • 2020-10-25
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多