关系多对多'Property [moedas]在此集合实例'

时间:2018-02-05 00:48:23

标签: php laravel many-to-many blade laravel-5.5

我想从moeda对象获取user(葡萄牙语硬币)数据。  但是我得到了一个error的说法,即房产莫达斯不存在。  我已经创建了所有要求数据透视表,模型,控制器和视图。

我的模特:

Moeda     

namespace leilao;

use Illuminate\Database\Eloquent\Model;

class Moeda extends Model
{
   public function users(){
         return $this->belongsToMany('leilao\User','moeda_user');
   }
}

用户

<?php

namespace leilao;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use leilao\Moeda;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
    public function moedas(){
        return $this->belongsToMany('leilao\Moeda','moeda_user');
    }
}

我的控制器

<?php

namespace leilao\Http\Controllers;

use Illuminate\Http\Request;
use leilao\User;
use leilao\Moeda;
class UsuarioController extends Controller
{
 $userCollection=User::with('moedas')->get();  
public function lista(){

    return view('lista')->with('users', $userCollection);
}

}

我的观点

<table class="table table-striped table-bordered table-hover">
<?php foreach ($users->moedas as $c): ?>
<tr>
   td><?= $c->currencia ?></td>
   <td><?= $c->valor ?></td>

</tr>
<?php endforeach ?>
</table>

数据透视表

迁移方法如下:

public function up()
{
      Schema::create('moeda_user', function(Blueprint $table)
{
  $table->increments('id');
  $table->integer('moeda_id')->unsigned()->nullable(); //unsingned não permite valores negativos
  $table->foreign('moeda_id')->references('id')
        ->on('moedas')->onDelete('cascade');

  $table->integer('user_id')->unsigned()->nullable();
  $table->foreign('user_id')->references('id')
        ->on('users')->onDelete('cascade');

  $table->timestamps();
});    }

1 个答案:

答案 0 :(得分:0)

您的班级名称与该关系的第一个参数之间的大小写不匹配:

// uppercase leilao\Moeda
public function moedas(){
    return $this->belongsToMany('leilao\Moeda','moeda_user');
}

// lowercase
class moeda extends Model