通过值获取id的方法 - Laravel

时间:2017-04-20 08:33:03

标签: php database laravel-5 eloquent

通过此查询,我按值在数据库中找到一个元素并获取id:

Model::where($table,'=',$value)->first()->id;

但我需要创建一个方法,因为我将此代码与其他模型一起使用;一个可能的例子:

public function getId($model,$table,$value) {
    ...
}

我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:2)

方法

public function getId($model, $table, $value) {
    return $model::where($table, $value)->first()->id;
}

用法

$id = getId('App\User', 'name', 'John Doe');

从您的代码中看起来您将此作为类方法。相反,您可以将其创建为全局帮助程序,以便您可以在任何位置访问它。

答案 1 :(得分:0)

我会创建一个特质

<?php

namespace App\Models\Traits;

trait GetIdByNameTrait
{
    public function scopeGetIdByName($query, $name)
    {
        return $query->where('name', $name)->first()->id;
    }
}

模型应该使用它:

use Traits\GetIdByNameTrait;

然后您可以在任何地方使用它;

$id = Model::getIdByName($value);