【问题标题】:Relation Many to Many 'Property [moedas] does not exist on this collection instance '关系多对多'此集合实例上不存在属性 [moedas]'
【发布时间】:2018-07-14 19:59:18
【问题描述】:

我想从user 对象中获取moeda(葡萄牙语中的硬币)数据。 但我收到error 说属性 moedas 不存在。 我已经创建了所有需求透视表、模型、控制器和视图。

我的模型:

萌达

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();
});    }

【问题讨论】:

  • 你有异常的堆栈跟踪吗?
  • 你能在Support/Collection的那个__get()方法中写一个日志语句吗?看看static 是什么类型,static::$proxies 里面有什么?
  • 它突然开始工作了!我刚刚使用这个表达式 users-&gt; as u 进行了迭代,我得到了这样的数据 u-&gt;moedas-&gt;someColoumn 。我几乎可以肯定我以前尝试过。我已经花了一周的时间试图解决这个问题。而不是突然无缘无故开始工作!非常感谢您的理解。
  • 哦,你有一组用户要先迭代。这是有道理的。至少它在工作哈哈

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


【解决方案1】:

您的类名和关系的第一个参数之间的大小写不匹配:

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

// lowercase
class moeda extends Model

【讨论】:

  • 我在格式化问题时犯了这个错字。我的代码不存在。感谢您的回答
  • 容易做,但至少可以解释你的错误,所以我想我应该提一下。
猜你喜欢
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 2020-11-12
  • 2019-03-23
相关资源
最近更新 更多