I use a pivot table in a project I'm working on to work with users.
For example: User::find(1)->works gives me the user's work with identifier 1.
The thing is, I want to filter these results with additional Pivot data.
Something like:
User::find(1)->works->pivot->where('active',1)->get();
In which the column that I set in the user_works pivot table is active.
This is my sister part of my User.php model:
<?php class User extends Cartalyst\Sentry\Users\Eloquent\User { public function works() { return $this->belongsToMany('Work','user_works')->withPivot('active')->withTimestamps(); } }
This is my sister part of my Work.php model:
<?php class Work extends Eloquent { public function users() { return $this->belongsToMany('User','user_works')->withPivot('active')->withTimestamps(); } }
This is my pivot table:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateUserWorksTable extends Migration { public function up() { Schema::create('user_works', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned()->default(0); $table->integer('work_id')->unsigned()->default(0); $table->enum('active',array('0','1'))->default(1); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('work_id')->references('id')->on('works')->onDelete('cascade'); $table->timestamps(); }); } public function down() { Schema::drop('user_works'); } }
Is there a way to get data without creating a new model for the pivot table?
Thanks in advance,
Edit: I can filter this path:
return User::find(1)->works()->where('user_works.active','=','1')->get();
I had to type the name of the raw table. But is there a better way to get this without using it?
pivot-table eloquent filtering laravel laravel-4
Arda
source share