2016-05-10 14 views
1

私は多対多の2つのメインテーブルとピボットテーブルを持っています。Laravel where多対多の関係

モデル 'タイプ'

public function attributes() 
    { 
     return $this->belongsToMany('App\Attribute', 'attribute_type'); 
    } 

モデル '属性'

public function types() 
    { 
     return $this->belongsToMany('App\Type', 'attribute_type'); 
    } 

ピボットテーブル 'attribute_typeに' 私はに属してランダムな順序で5つの属性を表示したい

Schema::create('attribute_type', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('type_id')->unsigned(); 
     $table->foreign('type_id')->references('id')->on('types'); 
     $table->integer('attribute_id')->unsigned(); 
     $table->foreign('attribute_id')->references('id')->on('attributes'); 
    }); 

idの種類< 10.

と例

$attribute->id 

ためは私に、「未定義のプロパティ:雄弁\ビルダー\ \データベースを照らす:: $ ID」を与え

答えて

2

クエリを実行すると、コレクションとを取得されなければならないすべてこのようなget()方法:

$attributes = Attribute::whereHas('types', function ($query) { 
     $query->where('id', '<', '10'); 
    })->orderByRaw("RAND()")->limit(5) 
    ->get(); 

今、あなたのようにあなたに別のクエリビルダを与えているクエリビルダを反復処理しようとしています$attribute

+0

の結果も変更されました( 'id'、 '<'、 '10'); 〜to( 'type_id'、 '<'、 '10'); – Estern