[英]Laravel Eloquent returns an empty collection on belongsToMany relationship
[英]Laravel 4 belongsToMany Relationship Returns Empty
我正在使用Laravel 4,並且正在努力建立許多關系。 這是我要執行的操作的示例。 在這里,我正在嘗試在用戶和組織之間建立多對多關系。
這是我的遷移文件,創建了一個users表,organizations表和一個位於兩者之間的數據透視表。
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email');
$table->string('password');
$table->timestamps();
});
Schema::create('organizations', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('organization_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('organization_id')->unsigned()->index();
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
我還使用了默認的用戶模型,並添加了belongsToMany關系。
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function organizations()
{
return $this->belongsToMany('Organization');
}
}
我創建了一個組織模型,其中關系朝着相反的方向發展。
class Organization extends \Eloquent {
protected $fillable = ['name'];
public function users()
{
return $this->belongsToMany('User');
}
}
問題是,如果我嘗試使用User :: find(1)-> organizations()進行查詢,當然,在添加示例數據之后,它總是返回為空數組,而使用Organization則相反::發現(1) - >用戶()。 奇怪的是,如果我嘗試執行類似Organization :: find(1)-> users()-> attach(1)的操作,則會在數據透視表中添加適當的行,因此知道存在關系。
關於查詢似乎為何無效的任何想法?
這就是您訪問關系的方式。 請嘗試執行以下操作:
$organisations = User::find(1)->organisations;
$users = Organisation::find(1)->users;
如果使用關系的方法版本,則還可以在查詢中添加其他內容。 但是要小心,您需要在其后加上get()
才能實際執行查詢。
// The same as just accessing the property
$organisations = User::find(1)->organisations()->get();
// With extra clauses
$organisations = User::find(1)->organisations()->where('created_at', '>=', '2010-01-01 00:00:00')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.