无法在Laravel数据透视表

时间:2016-12-15 17:49:00

标签: php mysql laravel eloquent laravel-5.3

我有一个Players / Lessonhours数据透视表,它保存从表单传递给它的所有值。然而,在我看来,它只显示了一些相关的记录。当我做一个$ players-> lessonhour-> toArray时,我似乎遇到了问题。当我执行$ lessonhours-> players-> toArray()时,我只获得了一些记录。我无法在关系设置中看到我做错了什么。显然需要一些东西。有人可以帮忙吗?

廷克:

Tinker view

MySQL的:

MySql view

玩家模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Collective\Html\Eloquent\FormAccessible;
use Carbon\Carbon;


class Players extends Model
{
    public $table = "players";

    protected $fillable = array('fname', 'lname', 'gender', 'birthdate');


    public function users()
    {
        return $this->belongsTo('App\User', 'users_id');
    }

    public function lessonhours()
    {
        return $this->belongsToMany('App\Lessonhours', 'lessonhour_player',    'lessonhours_id', 'players_id');
    }

    public function getFullName($id)
    {
        return ucfirst($this->fname ) . ' ' . ucfirst($this->lname);
    }

   protected $dates = ['birthdate'];

    public function setBirthdateAttribute($value)
    {
        $this->attributes['birthdate'] = Carbon::createFromFormat('m/d/Y',   $value);
    }
}


Lessonhours Model:

     <?php

namespace App;

use Illuminate\Database\Eloquent\Model;
 use Collective\Html\Eloquent\FormAccessible;
use Carbon\Carbon;

class Lessonhours extends Model
{
    protected $fillable = array('signup_date', 'players_id', 'packages_id');

    public $table = "lessonhours";

    public function players()
    {
        return $this->belongsToMany('App\Players', 'lessonhour_player',  'lessonhours_id', 'players_id');
    }

    public function packages()
    {
        return $this->belongsTo('App\Packages', 'packages_id');
     }

    public function hoursused()
    {
       return $this->hasMany('App\Hoursused', 'lessonhours_id');
    }

    protected $dates = ['signup_date'];

    public function setSignUpDateAttribute($value)
    {
        $this->attributes['signup_date'] = Carbon::createFromFormat('m/d/Y',     $value);
    }
}

这是视图显示的内容。列表中的每个人都应该至少有一个包,有些包含2个。

Player List

1 个答案:

答案 0 :(得分:1)

在玩家模型交换lessonhours_idplayers_id中:

public function lessonhours()
        {
            return $this->belongsToMany('App\Lessonhours', 'lessonhour_player', 'players_id', 'lessonhours_id');
        }