如何在laravel中排除一些特定的对象


How to exclude some particular objects in laravel

我的Laravel应用程序中有两个表。第一个是collection,第二个是q_collections。集合表包含一些对象。Q_collections有多对一字段,表示Q_collections表的集合对象id为c_id。我想从集合表中排除与q_collections相关的对象。有一个字段sd_item_id在两个表中都是通用的。我想使用这个sd_item_id来过滤表,以获得唯一的记录或那些在q_collections中不可用的记录。

表就像

//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');
}
}

你可以使用Laravel Query builder。

$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);

可能有其他方法执行此任务。我也是laravel的新手,所以我也说这段代码是完美的还是不完美的,但它肯定会起作用。