【问题标题】:Laravel - Get additional attributes of Many to Many tableLaravel - 获取多对多表的附加属性
【发布时间】:2019-09-12 20:11:46
【问题描述】:

我得到了以下表格

  • 演员
    1. 身份证
    2. 姓名
  • 统计
    1. 身份证
    2. 姓名
  • actor_stat
    1. actor_id
    2. stat_id
    3. 数量

我想,给定一个演员的名字,获取所有相关的数量。

演员模型:

class Actor extends Model
{
    public function stats()
    {
        return $this->belongsToMany('App\Stat', 'actor_stat')->withPivot('quantity');
    }

}

统计模型:

class Stat extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User', 'actor_stat')->withPivot('quantity');
    }
}

查询

    public function request(){
        $actors = Actor::where('name','Jack')->first();

        $stat = $actors->pivot->quantity; //??

        return response()->json(['actors' => $actors, 'stat' => $stat]);
    }

建议?

【问题讨论】:

  • 您要更新数据透视列吗?
  • 我想获取“数量”值。我的意思是,在我想要所有关联 actor-stat 和每个数量值之后,我会在第一个查询中得到一个演员。
  • 检查我的答案

标签: laravel eloquent many-to-many


【解决方案1】:

您可以像这样使用急切加载来加载相关表:

$actors = Actor::with('stats')->where('name','Jack')->first();

//do loop foreach actor state then you can access to quantity column

 foreach($actors->states as $state)
   $state->pivot->quantity; 

【讨论】:

    猜你喜欢
    • 2012-03-01
    • 1970-01-01
    • 2011-12-20
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多