【问题标题】:Retrieving data from linking table (Many to Many). Laravel从链接表中检索数据(多对多)。拉拉维尔
【发布时间】:2016-10-20 02:08:41
【问题描述】:

我试图从我的链接表 sfees 中获取数据,它由学生表中的 student_id 和 M_fees 表中的 mfee_id 组成。 我的模型是:

Student:
class student extends Model
{
    //
    protected $fillable = ['first_name','middle_name','last_name','address','contact','dob','grade_id','status','scholorship','admission_year','passout_year'];

    public function grade() {
    return $this->belongsTo(Grade::class);
  }

  public function M_Fees() {
    return $this->belongsToMany('App\M_Fees');
  }
}

M_fees:

class M_fees extends Model
{
     protected $fillable = ['fee_type','amount'];

     public function Student()
{
     return $this->belongsToMany('App\Student');
}
}

我的 sfees 表结构如下:

现在,我如何检索特定学生的 M_fees 'fee_type and amount)? 我在控制器中使用了以下内容:

$student=Student::all()->whereLoose('id',$sid);
foreach ($student->M_fees as $M_fees) {
    echo $M_fees->pivot->fee_type;
}

但它似乎不起作用。

谁能帮帮我?

【问题讨论】:

  • 您的数据透视表似乎是 sfeesfee_typeamount 表存在于哪个表中?
  • 它们存在于 M_fees 表中
  • 您是否尝试过不使用 pivot。我的意思是 echo $M_fees->fee_type; ?
  • 是的,它只是不断返回相同的错误异常:未定义属性:Illuminate\Database\Eloquent\Collection::$M_fees

标签: many-to-many laravel-5.2


【解决方案1】:

兄弟试试这个。有时您需要定义数据透视表名称。希望能有所帮助。请告诉我。

学生:

class student extends Model
{
    protected $table = "table_name";
    protected $fillable = ['first_name','middle_name','last_name','address','contact','dob','grade_id','status','scholorship','admission_year','passout_year'];

    public function grade() {
    return $this->belongsTo(Grade::class);
  }

  public function M_Fees() {
    return $this->belongsToMany('App\M_Fees','sfees');
  }
}

M_fees

class M_fees extends Model
{
     protected $table = "table_name";
     protected $fillable = ['fee_type','amount'];

     public function Student()
{
     return $this->belongsToMany('App\Student','sfees');
}
}

兄弟,我认为您的循环有问题。您必须遍历学生,并且必须为每个学生收取费用,金额。试试这个。

兄弟,我认为您的循环有问题。您必须遍历学生,并且必须为每个学生收取费用,金额。试试这个。

foreach ($student as $single_student) {

foreach ($single_student->M_fees as $M_fees) {

    echo $M_fees->pivot->fee_type;
}
}

希望它会起作用。让我知道

【讨论】:

  • 你检查过你的 $student 变量了吗?我的意思是有任何价值吗?
  • 我不确定您的 $student 变量是否有价值。查询正常吗?或者它应该看起来像 $student = Student::whereLoose('id',$sid)->get();
  • [{"id":1,"first_name":"Manish","middle_name":"","last_name":"Maharjan","address":"KTM","dob" :"2015-01-11","contact":"9801526987","scholarship":0.4,"admission_year":"2015-10-11","passout_year":"2010-10-11","grade_id" :1,"status":"Active","created_at":"2016-06-18 09:54:51","updated_at":"2016-06-18 09:54:51"}]
  • 你说得对,我的 $students 有问题。我改为 $student = Student::where('id',$sid)->first();而且效果很好。谢谢你的帮助! :)
  • 如果您在 $student 变量中有多个实体/行,那么您可以使用我刚刚编辑的答案。欢迎您@Anon :) :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 2017-08-24
  • 2018-12-19
  • 2019-02-21
  • 2017-06-16
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多