Laravel 多对多关系无效
Laravel many to many relation not working
我正在尝试从关系中获取数据,但只返回关系属性。
用户模型
class User extends Authenticatable {
use SoftDeletes; use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [ 'name', 'email', ];
/*
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [ 'password', 'remember_token' ];
/*
* Get the images for the store.
*/
public function stores() {
return $this->belongsToMany('App\Store', 'store_user');
}
}
店铺型号
public function users() {
return $this->belongsToMany('App\User');
}
枢轴 Table
public function up() {
Schema::dropIfExists('store_user');
Schema::create('store_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('store_id');
$table->integer('user_id');
$table->timestamps();
});
}
主元 table 和 id
之间的现有关系是准确的。
正在检索关系
$user = Auth::user();
$userStores = $user->stores;
$storesID = [];
foreach ($userStores as $store) {
$storesID[] = $store->id;
}
$builder->whereIn('store_id', $storesID);
这个returns:
Undefined property: App\User::$stores
我试过了
$userStores = $user->stores()->get();
但这会冻结页面,直到它抛出请求耗时超过 60 秒的错误。
你知道我做错了什么吗?
$user 似乎没有登录,也许先检查一下:
if (Auth::check()) {
}
问题 100% 出在您的 OwnerScope
文件中,您应该先查看该文件,然后查看您分配 $builder
值的那一行,我帮不上什么忙因为您没有包含任何一个的代码,所以在您更新您的问题并包含两者之前,我们只能做这些。
我正在尝试从关系中获取数据,但只返回关系属性。
用户模型
class User extends Authenticatable {
use SoftDeletes; use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [ 'name', 'email', ];
/*
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [ 'password', 'remember_token' ];
/*
* Get the images for the store.
*/
public function stores() {
return $this->belongsToMany('App\Store', 'store_user');
}
}
店铺型号
public function users() {
return $this->belongsToMany('App\User');
}
枢轴 Table
public function up() {
Schema::dropIfExists('store_user');
Schema::create('store_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('store_id');
$table->integer('user_id');
$table->timestamps();
});
}
主元 table 和 id
之间的现有关系是准确的。
正在检索关系
$user = Auth::user();
$userStores = $user->stores;
$storesID = [];
foreach ($userStores as $store) {
$storesID[] = $store->id;
}
$builder->whereIn('store_id', $storesID);
这个returns:
Undefined property: App\User::$stores
我试过了
$userStores = $user->stores()->get();
但这会冻结页面,直到它抛出请求耗时超过 60 秒的错误。
你知道我做错了什么吗?
$user 似乎没有登录,也许先检查一下:
if (Auth::check()) {
}
问题 100% 出在您的 OwnerScope
文件中,您应该先查看该文件,然后查看您分配 $builder
值的那一行,我帮不上什么忙因为您没有包含任何一个的代码,所以在您更新您的问题并包含两者之前,我们只能做这些。