简体   繁体   中英

How to exclude some particular objects in laravel

I have Two tables in my Laravel application. 1 is collection and second one is q_collections. Collection table contains some objects. q_collections has many to one field to collections , means q_collections table has id of collection objects as c_id.I want to exclude the objects from collection table which are related with q_collections. There is a field sd_item_id which is common in both the tables. I want to filter the tables using this sd_item_id to get unique records or those records which are not available in q_collections.

Tables are like

//Collection
class CreateCollection extends Migration {
public function up()
{
    Schema::create('collection', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name');
        $table->timestamps();

    });
}

public function down()
{
    Schema::drop('collection');

}
}
//q_collections
class CreateQCollections extends Migration {
public function up()
{
    Schema::create('q_collections', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('sd_item_id')->unsigned();
            $table->integer('qc_id')->unsigned();     // question collection id 
            $table->timestamps();
    $table->foreign('qc_id')->references('id')->on('collection');
    });
}

public function down()
{
    Schema::drop('q_collection');
}
}

You can use Laravel Query builder for this.

$collection_count=DB::table('q_collections')->where('sd_item_id','=',$item_id)->count();  
if($collection_count){  
    $sc=DB::table('q_collections')->where('sd_item_id','=',$item_id)->lists('qc_id');
}
else{
    $sc=array(0);
}
$collections=DB::table('collection')->whereNotIn('id',$sc)->get();
return Response::json($collections);

There may be some other ways to perform this task. I am also new to laravel so I also say that this code is perfect or not but it will surely work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM