php - 检查另一个表的字段状态 Eloquent

标签 php laravel eloquent

好的,我有一个自定义字段名称 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/

相关文章:

php - fopen()上传文件权限受目录添加组权限影响

php - 以 sha512 :1000: contain? 开头的 MYSQL 条目是什么

php - 在Symfony中获得Elasticsearch分数

php - 我收到 laravel mysql [2002] 连接错误

php - 这个 Blade 卫生是否正常工作(双花括号与三花括号)?

php - Laravel Eloquent 关系链

php - 将文本拆分为单个单词

mysql - SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails - laravel

php - 查找前 5 条记录的 Eloquent 查询

php - 在 Laravel 中使用同步分离数据透视表