我有3个表格描述书籍,人物和人物。这些看起来像这样:
book -> id, name
author -> id, name
book_person -> book_id, person_id, status (pivot table)
关系没问题,这是我的表
books person book_person
1 | book1 1|Peter id | book_id| person_id|status
2 | book2 2|Ren 1 | 1 | 1 | 1
3 | book3 2 | 1 | 2 | 0
3 | 2 | 2 | 1
4 | 3 | 2 | 1
whit laravel orm,我怎么才能得到身份= 1的人'2'(ren)
我在我的控制器上执行此操作
$bp = Book::find(2);
和我的观点
@foreach($bp->person as $p)
$p->pivot->id
$p->pivot->status
@endforeach
and this bring me
book_person (2,3,4) but i cant select only the status 1
如果book_person没有模型,我可以在哪里查询'where'查询?
答案 0 :(得分:0)
如果这些关系是多对多,您可以使用wherePivot
根据存储的数据透视表数据进行过滤。
$bp = Book::find(2);
$persons = $book->persons()->wherePivot('status', 1)->get();
你也可以急于加载它。并继续使用你查看。
$bp = Book::with(['persons' => function ($q) {
$q->wherePivot('status', 1);
}])->find(2);
答案 1 :(得分:0)
你没有提到模特关系。通过连接表
使用laravel DB查询$result = DB::table("person as p")
->join("book_person as bp","bp.person_id","=","p.id")
->join("book as b","bp.book_id","=","b.id")//if you want book detail also
->where('p.id','2')
->where('bp.status',1)
->get();