【发布时间】: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-> as u进行了迭代,我得到了这样的数据u->moedas->someColoumn。我几乎可以肯定我以前尝试过。我已经花了一周的时间试图解决这个问题。而不是突然无缘无故开始工作!非常感谢您的理解。 -
哦,你有一组用户要先迭代。这是有道理的。至少它在工作哈哈
标签: php laravel many-to-many blade laravel-5.5