好的,我有一个自定义字段名称 is_friend
我有3张 table
1. 用户
2. worker
3. friend
正如您猜测工作人员属于用户一样, friend 也属于工作人员。
我的查询,我想检查某个工作人员是否是当前登录用户的 friend
friend 架构:
Schema::create('tweets', function(Blueprint $table)
{
$table->increments('id');
$table->integer('targetID');
$table->integer('ownerID');
$table->timestamps();
}
从架构中可以看到,targetID 是工作人员的好友 ID,ownerID 是登录用户。
我的查询:
$worker = Worker::get('name');
在我的 worker 模型内
class Worker extends Eloquent{
protected $appends = array('is_friend');
public function user(){
return $this->belongsTo('user');
}
public function getIsFriendAttribute(){
if(Friend::where('targetID', $this->attributes['id'])
->where('ownerID', Auth::user()->id)->first()){
return true;
} else {
return false;
}
}
}
我正在使用自定义访问器来获取此自定义字段。 它可以工作,但非常丑陋,如果我查询 20 个工作人员,将会有 20 个查询只是为了检查此状态。
在 View 中,我可以访问
@if($worker->is_friend)
Your friend
@endif
最佳答案
好吧,我认为这个问题(n+1 问题)可以使用带有约束的预先加载来解决。
首先在Worker Model中定义好友关系。 就这样
class Worker extends Eloquent{
...
// This will get all the friends
public function friends(){
return $this->hasMany('Friend','targetID');
}
...
}
我们使用急切加载来处理n+1问题。 Click here and scroll down to Eager Load Constraints for documentation
// We use Eager loading constraints so that only two db queries are executed instead of n+1
$workers = Worker::with(array('friends' => function($query)
{
// So we constraint the ownerId to be current user id
$query->where('ownerID', Auth::user()->id);
}))->get();
现在在 View
@foreach ($workers as $worker)
@if(count($worker->friends) >0)
Your friend
@endif
@endforeach
关于php - 检查另一个表的字段状态 Eloquent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581158/