我有两个名为application和user的模型。
id |名称
id |名字
id | application_id | user_id |评论|评级|像
这是模型类
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\ModelValidator;
class Application extends ModelValidator
{
//
protected $table = "application";
public function user()
{
return $this->belongsToMany('App\User','application_user','application_id','user_id')->withPivot(['rating','like','comment'])->withTimestamps();
}
public function getComment()
{
$comments = array();
foreach ($this->user as $user) {
$comments[] = $user->comment;
}
return compact($comments);
}
}
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
class User extends ModelValidator implements AuthenticatableContract,CanResetPasswordContract
{
use Authenticatable,CanResetPassword;
protected $table = 'user';
public function application()
{
return $this->belongsToMany('App\Application')->withPivot(['rating','like','comment'])->withTimestamps();
}
}
但是当我运行下面的代码时,它会打印出空数组。
$apps = \App\Application::all();
foreach ($apps as $app) {
print_r($app->getComment());
}
为什么它返回空数组?
提前致谢
答案 0 :(得分:0)
只需改变你的关系
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\ModelValidator;
class Application extends ModelValidator
{
//
protected $table = "application";
public function user()
{
return $this->hasMany('App\ApplicationUser','application_id','id')
->withPivot(['rating','like','comment'])->withTimestamps();
}
}
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
class User extends ModelValidator implements AuthenticatableContract,CanResetPasswordContract
{
use Authenticatable,CanResetPassword;
protected $table = 'user';
public function application()
{
return $this->belongsToMany('App\Application')->withPivot(['rating','like','comment'])->withTimestamps();
}
}
像这样更改您的代码。
foreach ($apps as $app) {
print_r($app->user);
}
现在你从application_user表中获取数据,你得到了空的结果,因为你试图在用户表中找到一个数据,所以你的结果是空的。