Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a Twig function to create yii\db\Expression objects #3289

Merged
merged 2 commits into from
Sep 11, 2018

Conversation

carlcs
Copy link
Contributor

@carlcs carlcs commented Sep 11, 2018

Sometimes it’s not possible to pass a db expression as a string, becaus Yii escapes it and generates invalid SQL. yiisoft/yii2#553

Example use of the function:

{% set ids = [1639, 2079] %}

{% set orderByParam = ids ?
    dbExpression('FIELD(elements.id, ' ~ ids|reverse|join(', ') ~ ') desc, title asc') :
    'title asc' %}

{% set query = craft.entries
    .limit(50)
    .orderBy(orderByParam) %}

@brandonkelly
Copy link
Member

I like this. Can you rename the function to expression() instead of dbExpression() though?

@brandonkelly
Copy link
Member

(Worth noting that your particular example could also be achieved using the fixedOrder param though.)

@carlcs
Copy link
Contributor Author

carlcs commented Sep 11, 2018

@brandonkelly fixedOrder only works when using it in combination with ids() though. In this example the ids variable is an array of element IDs for entries that should show up first, but there are more entries returned.

@carlcs
Copy link
Contributor Author

carlcs commented Sep 11, 2018

{% set ids = blog.featuredBlogEntries.ids() %}

This makes the example clearer.

@brandonkelly
Copy link
Member

Ah gotcha, thanks for clarification! Though I realize expressions could be used for a variety of things so wouldn't have declined the PR anyway :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants