Craft 3のCustomフィールドでElementをどのようにクエリしますか? 私の最初の試みは、 craftcms/docs による:
$country = Entry::find()
->section('countries')
->where(['LIKE', 'code', 'CA'])->one()
しかし、これは例外をスローします。ここで code
はカスタムテキストフィールドです。また、スタック交換や他の多くの組み合わせについて、いくつかの回答を試みました彼らはCraft
2のためのもので、どちらも動作しません。
where句は、実際にはフィールドハンドルの代わりにデータベースフィールドを選択する必要があるクエリベースです。あなたがそのようにしなければならないところでそれをしたいとき
$country = Entry::find()->section('countries')->where([
'content.field_code' => ['like', 'CA']
])->all();
This is the correct documentation
right now.
編集:クエリと選択したすべての行を表示するために、
getRawSql()
関数を呼び出すことができます。あなたのコードを使用すると、SQLが例外をスローする理由がわかります
Edit2:
You don’t need to read the following part, these are just some
explanations to the content.field_code
part – if you
are interested in Craft go ahead if not skip it.
Not sure if you know that but Craft adds the prefix
field_
to every fieldhandle in the
content
table (the table where Craft stores your
entire content). So for every field you create the database
includes a column field_+$field->handle
that’s why
you have to include the field_
in before your handle
in the query above.
However if you are going to change that prefix for any reasons
you could use
Craft::$app->getContent()->fieldColumnPrefix
in
order to fetch the current column prefix. I doubt many people will
do this but I wanted to make sure you know it.
ElementQuery
( Entry ::
を実行したときに実際に呼び出すクラスは次のコードを含んでいます
find()
/**
* @var string|null The content table that will be joined by this query.
*/
public $contentTable = '{{%content}}';
これはハードコーディングされているので、クラフトの開発者だけがここで深刻な変更を加えることができます(Craftの構造を上書きしない限り)
So in the end: craft left joins the content
table
and selects all columns. That’s why you have to use
content.field_+$fieldHandle