Xinyi Lin
Xinyi Lin

Reputation: 11

How to set a value in join() rather a column name in Eloquent?

Here is my schemes:

user_familiarity

id, item_type, item_id, score, custom_score , ...

word

id , ...

user_familiarity stores familiarity score of any object, which can identified by (item_type, item_id)

for example:

item_type = 1001, item_id = 16 means table word and row's id is 16

Here is my code to select words with it's familiarity score:

$fam_table = UserFamiliarityModel::getTableName();
    return
        $query
        ->leftJoin($fam_table, function ($join) use($fam_table) {
            $join
            ->on(WordModel::getTableName() . '.id' ,'=',  "${fam_table}.item_id")
            ->on($fam_table . '.item_type' ,  1001);
        })
        ->addSelect(["${fam_table}.score", "${fam_table}.custom_score"]);

here is the sql that has been executed:

...
FROM
`word`
LEFT JOIN `user_familiarity` 
ON 
    `word`.`id` = `user_familiarity`.`item_id` 
AND `user_familiarity`.`item_type` = `1001`

and get errors :

Column not found: 1054 Unknown column '1001'

Upvotes: 0

Views: 60

Answers (2)

Ahmed Shams
Ahmed Shams

Reputation: 358

change on to where because you have specific value

Upvotes: 0

Xinyi Lin
Xinyi Lin

Reputation: 11

... I solve this problem by changing 'on' to 'where' :

->leftJoin($fam_table, function ($join) use($fam_table) {
        $join
        ->on(WordModel::getTableName() . '.id' ,'=',  "${fam_table}.item_id")
        ->where($fam_table . '.item_type' ,  1001);
    })

Upvotes: 1

Related Questions