【发布时间】:2015-04-10 00:35:37
【问题描述】:
我正在使用 Laravel 5,但在让 ->wherePivot() 处理多对多关系时遇到问题。当我dd() SQL 时,看起来 Eloquent 正在使用 `pose_state` 查找数据透视表中的记录。`pose_id` 为 null`。
我希望这是一个简单的错误,而不是错误。任何想法都表示赞赏。
数据库结构
姿势
id
name
type
状态
id
name
machine_name
姿势状态
pose_id
state_id
status
型号
姿势
<?php namespace App;
use DB;
use App\State;
use Illuminate\Database\Eloquent\Model;
class Pose extends Model {
public function states()
{
return $this->belongsToMany('App\State')
->withPivot('status_id')
->withTimestamps();
}
public function scopeWithPendingReviews()
{
return $this->states()
->wherePivot('status_id',10);
}
}
州
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class State extends Model {
public function poses()
{
return $this->belongsToMany('Pose')
->withPivot('status_id')
->withTimestamps();
}
}
PosesController 函数
public function listPosesForReview(){
$poses = Pose::withPendingReviews()->get();
dd($poses->toArray() );
}
SQL
select
`states`.*, `pose_state`.`pose_id` as `pivot_pose_id`,
`pose_state`.`state_id` as `pivot_state_id`,
`pose_state`.`status_id` as `pivot_status_id`,
`pose_state`.`created_at` as `pivot_created_at`,
`pose_state`.`updated_at` as `pivot_updated_at`
from
`states` inner join `pose_state` on `states`.`id` = `pose_state`.`state_id`
where
`pose_state`.`pose_id` is null and `pose_state`.`status_id` = ?
编辑
当我更新我的代码以删除它工作的范围时。感谢@Deefour 让我走上了正确的道路!也许范围还有其他我想念的东西。
public function pendingReviews()
{
return $this->states()
->wherePivot('status_id','=', 10);
}
又一次编辑
我终于让它工作了。上面的解决方案是给我重复的条目。不知道为什么会这样,但确实如此,所以我会坚持下去。
public function scopeWithStatusCode($query, $tag)
{
$query->with(['states' => function($q) use ($tag)
{
$q->wherePivot('status_id','=', $tag);
}])
->whereHas('states',function($q) use ($tag)
{
$q->where('status_id', $tag);
});
}
【问题讨论】:
标签: php laravel eloquent laravel-5