【问题标题】:Laravel Getting only certrain data from pivot tableLaravel 仅从数据透视表中获取某些数据
【发布时间】:2014-10-03 07:41:00
【问题描述】:

我正在使用 Laravel 来查询有分数的用户(eventscore 表中的行) 我想返回所有对事件有分数的用户,ID 为 3

是否可以只返回每个用户的分数,在数据透视表中找到(见下面的结果)

这是我正在使用的代码

    $persons = Person::whereHas('eventscore', function($q) {
        $q->where('id', 3);
    })->with('eventscore')->get();

    return $persons;

谢谢!

【问题讨论】:

  • 所以问题是如何使用枢轴score=3 获取事件分数或如何仅获取枢轴数据?而且这种关系应该称为events 而不是eventscore 才有意义。
  • 感谢您的回答!我确实只想获取此事件的分数.. 所以这就是 eventscore->pivot->score?谢谢!
  • 杰瑞克?还想帮我吗? :) 谢谢
  • 如果您只需要分数,我会建议将Person 与数据透视表本身(hasMany)链接起来的其他关系(甚至是简单的连接)。告诉我更多,您想如何使用它以及用于什么,然后我可以给您更准确的答案。
  • 好吧,我为每个事件都有一个特定的页面,事件 ID 是 (eventscore.id)。因此,我想查看该特定事件的每个人的姓名和得分。我希望这很清楚?我认为你做一个更简单的查询是对的..

标签: php sql laravel


【解决方案1】:

试试这个:

// Person model

// accessor for easy fetching the score from the pivot model
public function getScoreAttribute()
{
  return ($this->pivot && $this->pivot->score)
    ? $this->pivot->score
    : null;
}

// example usage for the event's page (I assume participants is the relation)
$event = Event::with('participants')->find(3);

// somewhere in the view template
@foreach ($event->participants as $participant)
  {{ $participant->name }} - score: {{ $participant->score }}
@endforeach

【讨论】:

  • 什么是getScoreAttribute?当你运行 $participant->score 时,laravel 会自动知道这一点吗?感谢你的回答!就是这个 ! :)
猜你喜欢
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多