获取所有没有翻译的键



我有这个实体:

class Keyword extends Model
{
use HasFactory;
protected $table = "keywords";
protected $fillable = [
'key',
'description',
'project_page_id'
];
public function keywordsTranslated()
{
return $this->hasMany(KeywordTranslated::class);
}
public function projectPage()
{
return $this->belongsTo(ProjectPage::class)->withDefault();
}
}

还有这个

class KeywordTranslated extends Model
{
use HasFactory;
protected $table = "keywords_translated";
protected $fillable = [
'translation',
'language_id',
'keyword_id'
];
public function keyword()
{
return $this->belongsTo(Keyword::class)->withDefault();
}
public function language()
{
return $this->belongsTo(Language::class)->withDefault();
}
}

对于特定的language,我想要得到所有没有keywordTranslatedkeywords

我试过了:

public function searchTranslatedKeys(
int $projectPageId,
int $curentPage,
int $languageId,
string $search = null
) {
$query = $this->model->newQuery();
$query->where('project_page_id', $projectPageId);
if ($search) {
$query->where('key', 'LIKE', "%{$search}%");
}
$query->doesntHave('keywordsTranslated');
$query->orderBy('id', 'DESC');
if ($search) {
return $query->get();
}
return $query->get()->forPage($curentPage, 20);
}

但是在这种情况下,我的返回是空的。

例如,在关键字中我有:

id          key                description
1           addItem            description for this item
2           deleteItem         description for this item 
3           editItem           description for this item  

In kewordtranslations:

translation             keyword_id                     language_id
Add item                1                               1
Add item new            1                               2
Delete item             2                               1

我想获得没有语言2的所有键,对于前面的例子,我应该收到2个id = 2 &3,因为这些键没有该语言的kewordTranslated。如果语言id为1,我应该只得到id = 3的关键字,因为这个关键字没有这个语言的kewordTranslated

你可以使用whereDoesntHave

它基于关系的缺失限制你的结果:

代替:

$query->doesntHave('keywordsTranslated');

可以使用:

$query->whereDoesntHave('keywordsTranslated',function ($query) use ($languageId) {
$query->where('language_id','=',$languageId);
});

相关内容

  • 没有找到相关文章

最新更新