通过此查询,我按值在数据库中找到一个元素并获取id:
Model::where($table,'=',$value)->first()->id;
但我需要创建一个方法,因为我将此代码与其他模型一起使用;一个可能的例子:
public function getId($model,$table,$value) {
...
}
我该怎么办?
谢谢!
答案 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);