如何在Laravel Pivot模型上调用函数 [英] How to Call function on laravel pivot model

查看:55
本文介绍了如何在Laravel Pivot模型上调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在课程中用户与课程之间具有多对多关系,并且出勤率表基于该关系的情况下,吸引每位用户参加.但是我无法直接调用 $ user-&p; pivot-> attendance(); ,因此我不得不直接调用自身的数据透视对象,因此您可以在其中调用函数答案

I was trying to get the attendance of each user in a course where the users and the courses have many to many relationship and the attendance table is based on the relationship. But i couldn't call $user->pivot->attendance(); directly i had to call for the pivot object it self so i can call a function to it as you can see in the answer

以下是我的数据库方案的示例

The Following is a sample of my Database scheme

我需要跑步

$users=$course->users;
foreach($users as $user)
{
    $user->pivot->attendance(); //error in this line
}

此行给出错误

调用未定义的方法Illuminate \ Database \ Query \ Builder :: attendance()

Call to undefined method Illuminate\Database\Query\Builder::attendance()

用户

id
name
etc

课程

id
name
startDate
endDate

course_user

course_user

id
course_id
user_id
payment
regDate
status

用户出席

id
course_user_id
time
inOrOut

这是CourseUserPivot类

And here is the CourseUserPivot Class

class CourseUserPivot extends Eloquent {


    protected $table ="course_user";



    public function course()
    {
        return $this->belongsTo('Course'); 
    }

    public function user()
    {
        return $this->belongsTo('User'); 
    }

    public function attendance()
    {
        return $this->hasMany('Userattendance','course_user_id');
    }
}

P.S:$ user-> pivot->付款有效并显示属性,但我无法调用方法

P.S: $user->pivot->payment works and displays the attribute but i cant call methods

推荐答案

您不能使用 $ user-> pivot-> attendance(); ,因为这会导致用户对象出勤不在枢轴对象上

You can't use $user->pivot->attendance(); as this calls attendance on the user object not on the pivot object

您将必须获取数据透视表对象,然后像这样调用函数

You will have to fetch the pivot object then call the function like so

CourseUserPivot::find($user->pivot->id)->attendance();

让用户在使用withPivot()函数的位置将ID包含在数组中

make user that where you used withPivot() function you include the id in the array

喜欢

class Course{
...
...
public function users()
    {
        return $this->belongsToMany('Candidate')
                    ->withPivot('id',
                    'summary',
                    'status',
                    'payment'

                    );
    }
}

这篇关于如何在Laravel Pivot模型上调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆