elowenjoin使用带有n query的“using”子句

dgsult0t  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(271)

我正在使用slim框架和数据库。
我想做点什么 JOIN 查询方式 USING 克劳萨。假设给定了sakila数据库。示意图:

如何在雄辩模型中加入using子句(not on)?

SELECT film_id,title,first_name,last_name 
FROM film_actor 
INNER join film USING(film_id) -- notice 
INNER join actor USING(actor_id) -- notice

我想要的是一个精确的1查询急切加载。api中描述的雄辩关系的使用并没有达到我的期望,因为任何渴望的关系都使用n+1查询。我想减少对数据库的io。
电影演员模型:

class FilmActor extends Model
{
    protected $table = 'film_actor';
    protected $primaryKey = ["actor_id", "film_id"];
    protected $increamenting = false;
    protected $appends = ['full_name'];

    // i need to make it in Eloquent model way, so it easier to manipulate
    public function getFullNameAttribute()  
    {
        $fn = "";
        $fn .= isset($this->first_name) ? $this->first_name ." ": "";
        $fn .= isset($this->last_name) ? $this->last_name ." ": "";
        return $fn; 
    }

    public function allJoin()
    {
        // how to join with "USING" clause ?
        return self::select(["film.film_id","title","first_name","last_name"])
            ->join("film", "film_actor.film_id", '=', 'film.film_id')  
            ->join("actor", "film_actor.actor_id", '=', 'actor.actor_id');  

        //something like
        //return self::select("*")->joinUsing("film",["film_id"]);
        //or
        //return self::select("*")->join("film",function($join){
        //    $join->using("film_id");
        //});
    }
}

所以,在控制器中我可以得到如下数据

$data = FilmActor::allJoin()  
        ->limit(100)  
        ->get();`

但如果我需要增加额外的行为(比如 where 或者 order ).

$data = FilmActor::allJoin()
        ->where("film.film_id","1")   
        ->orderBy("film_actor.actor_id")  
        ->limit(100)  
        ->get();`

我需要传递表名以避免字段不明确。不好的。所以我想进一步使用,我可以做

$kat = $request->getParam("kat","first_name");  
// ["film_id", "title", "first_name", "last_name"]  
// from combobox html  
// adding "film.film_id" to combo is not an option  
// passing table name to html ?? big NO

$search = $request->getParam("search","");
$order = $request->getParam("order","");
$data = FilmActor::allJoin()
        ->where($kat,"like","%$search%")   
        ->orderBy($order)  
        ->limit(100)  
        ->get();`
gudnpqoy

gudnpqoy1#

你可以试着在代码中找出是可能的 USING JOIN ,或添加一些代理字典:

$kat_dict =  ["film_id" => "film.film_id", "title"=> 'title', "first_name" => 'first_name', "last_name" => 'last_name'];

$kat = $kat_dict[$request->getParam("kat","first_name")];

顺便说一句:更好的方法是使用arr::get($arr,$index,$default)这样的函数(参见at代码示例)

相关问题