also using bootstrap 5.3, i find if i do this to the img it squishes it too much
Assistant
The issue you're encountering is due to the fixed height (200px) applied to the image using CSS, which forces the image into a fixed height and thus distorts its aspect ratio, making it appear squished.
How to fix this while using Bootstrap 5.3:
Bootstrap's .card-img-top class is typically used to make the image span the card's width naturally while maintaining its aspect ratio. Overriding height alone scrambles the ratios unless the width is specifically controlled.
Recommendations:
1. Use max-height instead of height, and set width: 100% for the image
This will ensure the image width is responsive within the column/card width, and the height adjusts proportionally without squishing.
css
section.related-articles img.image-header {
max-height: 200px;
width: 100%;
object-fit: cover; /* or contain depending on your preference */
}
max-height: 200px; — restricts the height to max 200px but allows smaller if needed to maintain shape.
width: 100%; — forces the image to fill the card's width responsively.
object-fit: cover; — this will crop the image to fill the container without distortion.
If you want the whole image visible and don't want cropping, use object-fit: contain, but expect letterboxing (empty space).
2. Using Bootstrap's ratio helper classes
Bootstrap 5.3 introduces ratio utilities which maintain fixed aspect ratios for responsive images/containers.
You mention a .square class on various parts including the image — make sure this class doesn't apply fixed widths/heights that conflict. If it’s forcing fixed dimensions, it may make the image squish regardless of the CSS above.
If you want, I can help you write updated CSS based on your .square class and your card layout to get the best aspect ratio usage. Just share that CSS or describe .square.
User
content model
code
class Content extends ActiveRecord
{
public ?array $tagNames = null;
public function rules(): array
{
return [
['tagNames', 'each', 'rule' => ['string']],
['tagNames', 'safe'],
];
}
public function beforeValidate(): bool
{
if (!parent::beforeValidate())
{
return false;
}
if (is_string($this->tagNames))
{
$decoded = json_decode($this->tagNames, true);
if (is_array($decoded))
{
$this->tagNames = $decoded;
}
else
{
$this->tagNames = null;
}
}
return true;
}
public function afterFind()
{
parent::afterFind();
// ...custom code here...
//LogHelper::debug('Loading tags for content ID: ' . $this->id);// TODO
//$this->tagNames = array_map(fn($tag) => $tag->name, $this->tags);
$this->tagNames = array_map(function($tag)
{
// or $tag->slug if you use slug for editing
return $tag->name;
}
, $this->tags);
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
// ...custom code here...
$transaction = \Yii::$app->db->beginTransaction();
try
{
// Unlink all existing tags and relink new ones
$this->unlinkAll('tags', true);
// No tags to link
if (!is_array($this->tagNames) || empty($this->tagNames))
{
$transaction->commit();
return;
}
$existingTags = Tags::find()->where([
'name' => $this->tagNames
])->indexBy('name')->all();
foreach ($this->tagNames as $tagName)
{
$tagName = trim($tagName);
if ($tagName === '')
{
continue;
}
if (isset($existingTags[$tagName]))
{
$tag = $existingTags[$tagName];
}
else
{
$tag = new Tags();
$tag->name = $tagName;
/**
* Yii2 Inflector provides methods to convert strings between formats,
* generate URL-friendly slugs, and pluralize or singularize words.
* Example: 'My First Post' => 'my-first-post' (slug),
*
* 'postCategory' => 'post_category' (underscore),
* 'categories' => 'category' (singularize).
*/
$tag->slug = Inflector::slug($tagName);
if (!$tag->save())
{
continue;
}
$existingTags[$tagName] = $tag;
}
$this->link('tags', $tag);
}
$transaction->commit();
}
catch (Throwable $e)
{
$transaction->rollBack();
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'content_model_afterSave_error_');
//throw $e;
}
}
public function getTags(): ActiveQuery
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
}
Assistant
Thanks for the detailed code and explanation. You want to:
For each artist (Content records with template = 'artist'),
Get their related works (other Content entries related by the artist’s tag/category),
And show 3 selected works per artist on the artist index or view.
Let's break down your requirements:
Artists are Content models with 'template' => 'artist'.
Each artist's "name" is also used as a tag.
You want to find Contents (works) that have the tag with the artist's name (e.g., "bob") — i.e., related works tagged with the artist's tag.
Show 3 works per artist.
Step 1: Add a method in Content (Artist) model to get selected works by tag name
Since you have a relation getTags(), and tags relate to contents via content_tags pivot, query those Contents that share the tag with tag.name = $artistName.
In Content model (artist):
php
/**
* Get selected works for the artist
*
* @param int $limit number of works to retrieve
* @return Content[]
*/
public function getArtistSelectedWorks(int $limit = 3): array
{
if (empty($this->title)) {
// fallback if no title
return [];
}
// Find the tag that matches the artist name (assumed from title)
$tagName = trim($this->title);
// Find the tag record
$tag = Tags::findOne(['name' => $tagName]);
if (!$tag) {
return []; // no tag found, no works
}
// Find content items tagged with this tag
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tag->id])
->andWhere(['!=', 'c.id', $this->id]) // exclude current artist content itself
->andWhere(['c.status' => 1])
->limit($limit)
->all();
}
User
put this where
code
/**
* Get selected works for the artist
*
* @param int $limit number of works to retrieve
* @return Content[]
*/
public function getArtistSelectedWorks(int $limit = 3): array
{
if (empty($this->title)) {
// fallback if no title
return [];
}
// Find the tag that matches the artist name (assumed from title)
$tagName = trim($this->title);
// Find the tag record
$tag = Tags::findOne(['name' => $tagName]);
if (!$tag) {
return []; // no tag found, no works
}
// Find content items tagged with this tag
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tag->id])
->andWhere(['!=', 'c.id', $this->id]) // exclude current artist content itself
->andWhere(['c.status' => 1])
->limit($limit)
->all();
}
Assistant
You should put this method inside your Content ActiveRecord class. Typically, add it anywhere among your public methods in Content.php, for example right after your existing relations or after getTags():
Example placement inside the Content class:
php
class Content extends ActiveRecord
{
// ... existing properties and methods ...
public function getTags(): ActiveQuery
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
/**
* Get selected works for the artist
*
* @param int $limit number of works to retrieve
* @return Content[]
*/
public function getArtistSelectedWorks(int $limit = 3): array
{
if (empty($this->title)) {
return [];
}
$tagName = trim($this->title);
$tag = Tags::findOne(['name' => $tagName]);
if (!$tag) {
return [];
}
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tag->id])
->andWhere(['!=', 'c.id', $this->id])
->andWhere(['c.status' => 1])
->limit($limit)
->all();
}
// ... other methods ...
}
Tip:
This method will then be accessible on any Content instance representing an artist, e.g. $artist->getArtistSelectedWorks() or via magic getter $artist->artistSelectedWorks.
If you'd like a magic getter, add also this:
php
public function getArtistSelectedWorksProperty()
{
return $this->getArtistSelectedWorks();
}
or just access as $artist->getArtistSelectedWorks() explicitly.
User
so its in content model but im querying content model?
Assistant
Yes, exactly!
Your Content model represents all types of content including artists, artworks, etc. You are:
Querying Content records where 'template' = 'artist' (to get artists)
Then for each such artist, you call the method inside the same Content model (getArtistSelectedWorks) to fetch related Content records that represent their works.
Why does this make sense?
Both artists and their works are stored in the same Content table/model.
The difference is in their template attribute (e.g., 'artist' or maybe 'work' or other).
The tagging system links the artist (by artist’s name tag) to all related works (which also have that tag).
So even though you query Content initially for artists, you’re querying Content again inside getArtistSelectedWorks() but filtered by tag name linked to that artist.
Diagrammatically
code
Content (artist) ---tagged by--> Tag (artist name)
Content (works) ---tagged by--> same Tag (artist name)
Artist contents have a title = artist name/tag.
Works contents have the same tag.
getArtistSelectedWorks() finds works linked to the artist tag (artist name), excluding the artist record itself.
Great question! Let's carefully walk through how these methods and your schema relate, and why the getArtistSelectedWorks() method uses the title as the tag name to find works, versus the more generic getRelatedContent() method.
Your database schema overview
content table: stores all kinds of content, including artists, works, posts, etc.
tags table: stores tag records with id, name, slug.
content_tags join table (pivot) relates contents to tags: (content_id, tag_id).
What does the code in Content model do?
1) getTags() relation
php
public function getTags(): ActiveQuery
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
Defines a many-to-many relation from a Content record to its Tag records.
Via the join table content_tags where each (content_id, tag_id) connects a content item with a tag.
Example: a Content with ID 123 has tags (Blue, Art, Bob) — linked by rows in content_tags.
2) getRelatedContent(int $limit = 5) method
php
public function getRelatedContent(int $limit = 5): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds))
{
return [];
}
return Content::find()
->joinWith('tags t')
->andWhere(['t.id' => $tagIds])
->andWhere(['<>', 'content.id', $this->id]) // exclude current content itself
->distinct()
->limit($limit)
->all();
}
This method finds other Content records which share any tag with the current Content.
It:
User
the title being the same as teh tags will not work
Assistant
Got it — if using the artist’s title as the tag name is not reliable or possible, you’ll need a more robust way to relate artists and their works via tags.
Your situation:
Content table stores artists and works.
Artists and works are linked by shared tags.
But artist's title does not reliably match a tag name.
You want to find works belonging to an artist based on shared tags, without relying on matching title to tag name.
Alternative approaches to link artists and their works via tags:
1) Use the actual tags linked to the artist content (the $this->tags relation)
Since your Content model already has
php
public function getTags(): ActiveQuery
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
you can rely on the artist content’s set of tags as the linking point:
php
public function getArtistSelectedWorks(int $limit = 3): array
{
// Get tag IDs of this artist content
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
// Find other works tagged by ANY of the artist's tags, excluding this artist content
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tagIds])
->andWhere(['!=', 'c.id', $this->id])
->andWhere(['c.status' => 1])
->distinct()
->limit($limit)
->all();
}
This matches your getRelatedContent() style logic.
Assumes the artist's tags accurately represent which works belong to them.
No reliance on title.
2) Assign (and enforce) an explicit for artist contents and their works
User
public function getArtistSelectedWorks(int limit = 3): array
{
// Get tag IDs of this artist content
tagIds = array_map(fn(tag)=>tag->id, $this->tags);
code
if (empty($tagIds)) {
return [];
}
// Find other works tagged by ANY of the artist's tags, excluding this artist content
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tagIds])
->andWhere(['!=', 'c.id', $this->id])
->andWhere(['c.status' => 1])
->distinct()
->limit($limit)
->all();
}
explain the query
Assistant
Certainly! Let's break down and explain the query generated by your getArtistSelectedWorks() method step-by-step.
Your method:
php
public function getArtistSelectedWorks(int $limit = 3): array
{
// Get tag IDs of this artist content
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
// Find other works tagged by ANY of the artist's tags, excluding this artist content
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tagIds])
->andWhere(['!=', 'c.id', $this->id])
->andWhere(['c.status' => 1])
->distinct()
->limit($limit)
->all();
}
What SQL query does this generate approximately?
Assuming:
The current artist content ID is :artist_id (PHP $this->id)
The $tagIds is an array of tag IDs assigned to this artist content, e.g. [5, 7, 10]
The SQL roughly looks like:
sql
SELECT DISTINCT c.*
FROM content c
INNER JOIN content_tags ct ON ct.content_id = c.id
WHERE ct.tag_id IN (5, 7, 10) -- tags assigned to the artist content
AND c.id != :artist_id -- exclude current artist content itself
AND c.status = 1 -- filter only published/enabled contents (works)
LIMIT 3;
This retrieves the IDs of the tags associated with the current artist content.
Example: if artist content is tagged with tags "modern", "abstract", "bob", this pulls their tag IDs [5,7,10].
2.
User
code
Assuming:
The current artist content ID is :artist_id (PHP $this->id)
The $tagIds is an array of tag IDs assigned to this artist content, e.g. [5, 7, 10]
The SQL roughly looks like:
SELECT DISTINCT c.*
FROM content c
INNER JOIN content_tags ct ON ct.content_id = c.id
WHERE ct.tag_id IN (5, 7, 10) -- tags assigned to the artist content
AND c.id != :artist_id -- exclude current artist content itself
AND c.status = 1 -- filter only published/enabled contents (works)
LIMIT 3;
so its based off the content? and what tags are saved within that content activeRecord?
Assistant
Exactly!
Here's the key point:
Each Content record (whether an artist, a work, a post, etc.) can have tags attached via the pivot table content_tags.
So when you load a Content ActiveRecord ($content), $content->tags gives you an array of Tag ActiveRecord objects that are connected to that content.
You are getting the list of tag IDs attached to the current content, for example, an artist.
If this content is the artist "Bob," $this->tags will include Tag records like ("bob", "abstract", "modern") — whatever tags are assigned to that artist content.
The SQL query generated then:
Searches the content table for other content records (like works) linked to any of those same tags.
Meaning, any other content sharing one or more tags with this artist content.
Excludes the artist record itself (c.id != :artist_id)
Only picks contents where status = 1 (active)
Limits the result.
So yes:
The query is based on the tags saved on this particular Content ActiveRecord instance.
Tags are saved in the many-to-many relation between the content and tags via the content_tags table.
Visual example:
content_id
tag_id
101 (artist Bob)
5 ("bob")
101 (artist Bob)
8 ("sculpture")
202 (work 1)
5 ("bob")
202 (work 1)
9 ("modern")
203 (work 2)
8 ("sculpture")
203 (work 2)
10 ("abstract")
$artistContent->tags returns tag IDs [5,8]
Query looks for content tagged by 5 or 8 excluding 101.
Returns content IDs 202 and 203 (works related to "Bob").
Summary:
The tags stored on the Content ActiveRecord are the basis for the query, defining which works relate to that artist.
This relies on tagging your artists with artist-specific tags, so their works can share those tags, allowing the query to fetch them.
If your artist content doesn't have meaningful tags assigned, the query won't find works correctly — so tag management consistency is the key here.
return Content::find()
->joinWith('tags t')
->andWhere(['t.id' => $tagIds])
->andWhere(['<>', 'content.id', $this->id])// exclude the current content
->distinct()
->limit($limit)
->all();
Assistant
Great question! Both snippets aim to fetch Content records related by tags, but they differ in how they join the tags table and their query syntax. Let's examine each difference.
Manually joins the pivot tablecontent_tags (ct) to content (c).
Filters by ct.tag_id in $tagIds.
Excludes the current content ID.
Ensures status = 1 (active).
Uses alias('c') to give the content table a short alias.
Returns distinct results.
Equivalent SQL fragment:
sql
SELECT DISTINCT c.*
FROM content c
INNER JOIN content_tags ct ON c.id = ct.content_id
WHERE ct.tag_id IN (...)
AND c.id != :current_id
AND c.status = 1
LIMIT :limit;
Uses joinWith('tags t'), which joins the tags table via the content_tags pivot table automatically, because of the relation defined in your Content model:
php
User
so which is best
Assistant
Both approaches are valid, but which one is best depends on your specific needs. Here’s a quick guideline to choose the best one for your use case:
When manual join on pivot table (content_tags) is better:
This keeps Yii relations, lets you add tag conditions cleanly, and clarifies intent.
/
Assistant
Yes, exactly! Your current getRelatedContent() method is close to the recommended pattern. To better leverage Yii's joinWith() with explicit condition inside the relation, it’s a good idea to rewrite it like this:
php
public function getRelatedContent(int $limit = 5): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
return self::find()
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['id' => $tagIds]);
}])
->andWhere(['<>', 'content.id', $this->id]) // exclude current content itself
->andWhere(['content.status' => 1]) // ensure published only
->distinct()
->limit($limit)
->all();
}
Why is this better?
joinWith(['tags' => function ($query) use ($tagIds) {...}]) lets you add conditions to the related tags table explicitly, filtering tags inside the join.
Keeps your code clean, clear, and takes full advantage of Yii's ActiveRecord relations.
Still filters out the current content and requires published status.
Returns Contents sharing any of the tags assigned to this content.
Uses distinct() to avoid duplicates caused by multiple tag matches.
Summary
Your current method is fine and clear.
Wrapping your tag filtering inside the closure for the tags relation’s query is preferred.
This is fully compatible, easy to maintain and extend if you want to add more tag-based filters or sorting later.
If you want, I can help generate direct SQL or suggest indexes for better performance!
User
ok how do i use this new function in controller and view for suggested artists work
Assistant
Great! You have your getRelatedContent() method in the Content model, which returns related content (e.g., works related to an artist).
How to use getRelatedContent() in your controller and view
1. In your controller action (for example, actionView or wherever you display an artist):
php
public function actionView($id)
{
$model = Content::findOne($id);
if (!$model) {
throw new NotFoundHttpException('The requested page does not exist.');
}
// Get related works for the artist/content, limit 3 or whatever you want
$relatedWorks = $model->getRelatedContent(3);
return $this->render('view', [
'model' => $model,
'relatedWorks' => $relatedWorks,
]);
}
2. In your view file (view.php or a partial for artist detail)
Below your main artist content display, add something like:
Call $model->getRelatedContent($limit) in your controller.
Pass results to the view.
Loop over them to display suggested/related works.
Use placeholder images if needed.
Use joinWith('tags') inside your model method for efficient querying, as you already do.
If you want help making a widget or reusable partial for showing related works, just ask!
User
is what I hhave so far
code
public function actionIndex()
{
// Set Page title for the browser tab/page title and page header.
$pageTitle = \Yii::t('app', 'articles');
// Set Meta Data for website title, keywords, description and prepend site name(bool).
$this->setMeta($pageTitle, 'articles, article, news');
// Set page breadcrumbs. (optional)
//\Yii::$app->layoutManager->addBreadcrumb($pageTitle);// page now.
$artistQuery = Content::find()
->where(['template' => 'artist', 'status' => 1])
->orderBy(['title' => SORT_ASC]);
$artistDataProvider = new ActiveDataProvider([
'query' => $artistQuery,
'pagination' => [
'pageSize' => 9,
],
]);
return $this->render('index', [
'artistDataProvider' => $artistDataProvider,
]);
}
Assistant
Your actionIndex() is correctly querying all artists with template 'artist' and status = 1, ordering by title, and passing a data provider for pagination to the view.
To show three selected related works per artist on that index page, you have some choices:
Option 1: Eager load related works inside the index query (advanced)
This requires complex eager loading or batch queries with tags.
Not trivial because related works depend on tags dynamically.
Can cause N+1 query problem if each artist loads related works separately.
Option 2: In your index view, for each artist, call your getRelatedContent(3) method to fetch three related works as needed.
Simple to implement.
May incur N+1 queries (one per artist), so OK for small pages or add caching.
Example — Your index view snippet (to render artists and their selected works):
but I also need to query for hte artist to start the $model
code
public function actionIndex()
{
// Set Page title for the browser tab/page title and page header.
$pageTitle = \Yii::t('app', 'articles');
// Set Meta Data for website title, keywords, description and prepend site name(bool).
$this->setMeta($pageTitle, 'articles, article, news');
// Set page breadcrumbs. (optional)
//\Yii::$app->layoutManager->addBreadcrumb($pageTitle);// page now.
$artistQuery = Content::find()
->where(['template' => 'artist', 'status' => 1])
->orderBy(['title' => SORT_ASC]);
$artistDataProvider = new ActiveDataProvider([
'query' => $artistQuery,
'pagination' => [
'pageSize' => 9,
],
]);
return $this->render('index', [
'artistDataProvider' => $artistDataProvider,
]);
}
Assistant
Yes, exactly!
Explanation:
Your $model is one Content ActiveRecord instance — e.g., one artist.
To call $model->getRelatedContent(4), you first need to get that particular artist record ($model).
In your actionIndex(), you are querying multiple artists via $artistQuery and wrapping that in a data provider $artistDataProvider.
How to use getRelatedContent() in your case:
When showing the artist index page, you have many artists (not just one).
You cannot call one $model->getRelatedContent() because there are many artists.
Instead, in your view where you loop through each artist from the data provider, call the method for each artist individually.
Example usage in the index view (pseudo-code)
php
<?php foreach ($artistDataProvider->getModels() as $artist): ?>
<h2><?= \yii\helpers\Html::encode($artist->title) ?></h2>
<?php
$relatedContent = $artist->getRelatedContent(4);
?>
<?php if ($relatedContent): ?>
<ul>
<?php foreach ($relatedContent as $work): ?>
<li><?= \yii\helpers\Html::encode($work->title) ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>No related works found.</p>
<?php endif; ?>
<?php endforeach; ?>
<?= \yii\widgets\LinkPager::widget(['pagination' => $artistDataProvider->pagination]) ?>
Summary
In your controller, you query many artists using Content::find() with the condition 'template' => 'artist'.
You pass the data provider artistDataProvider to the view.
In the view, for each artist $artist, call $artist->getRelatedContent(4) (or whatever limit) to get their works.
Display those related works accordingly.
Optional: Avoid N+1 queries
Calling getRelatedContent() for each artist causes one query per artist (N+1 problem).
To optimize:
Cache the related content inside getRelatedContent() method.
Batch load tags for all artists beforehand with with('tags').
Or design a batch query that fetches related works for all artists in one or few queries (more complex).
If you want, I can help you implement caching or batch querying!
User
i need the actionIndex() code
Assistant
Here’s a clean and practical actionIndex() for your artist listing page, which queries artists and passes them to the view:
php
public function actionIndex()
{
$pageTitle = \Yii::t('app', 'artists'); // or 'articles' if you prefer
$this->setMeta($pageTitle, 'artists, art, gallery'); // Update meta as needed
// Query all published artists ordered by title, eager loading tags to minimize queries on getRelatedContent()
$artistQuery = Content::find()
->where(['template' => 'artist', 'status' => 1])
->with('tags') // eager load tags relation for performance
->orderBy(['title' => SORT_ASC]);
$artistDataProvider = new ActiveDataProvider([
'query' => $artistQuery,
'pagination' => [
'pageSize' => 9,
],
]);
// Pass the data provider to the view; related works fetched per artist in the view
return $this->render('index', [
'artistDataProvider' => $artistDataProvider,
]);
}
Explanation
Loads artists (Content with template = 'artist' and status = 1).
Eager loads tags (->with('tags')) so calling $artist->getRelatedContent() in the view won't trigger extra queries for tags.
Pagination set to 9 per page.
Related works for each artist are fetched dynamically in the view using $artist->getRelatedContent($limit).
This is my code, i dont want to change my layout, please help fix it
code
Assistant
Thanks for sharing your layout and code! To integrate the related artist works (getRelatedContent() or your artistSelectedWorks) into your existing layout without changing it much, you mostly need to:
Make sure $model->artistSelectedWorks returns the related works array (your existing method or computed property).
Add use yii\helpers\Url; at the top of your view, since your current code calls Url::to().
Fix any minor PHP tag issues and keep your HTML structure intact.
Here is your adjusted view code, incorporating fixes and minimal changes:
php
User
i dont get it.. so if the content activeRecord for artist has the tag bob, and i create another content activeRecord with bob. should they not be joined?
Assistant
Exactly! Here's how it works conceptually and practically in your setup:
What happens in your tagging and content system?
Tags are shared labels attached to many Content records via the pivot tablecontent_tags (content_id, tag_id).
If one Content record (say artist "Bob") has the Tag named "bob", and
Another Content record (say a work) also has the same Tag "bob",
Then both Contents are connected through that shared tag.
So yes:
Both Contents are related by the common tag"bob".
Your queries joining through content_tags on tag_id will find both records belong to that tag.
How does your query (or method) pick this up?
Example:
Artist content record with ID 1 has tag bob with tag_id = 100.
Artwork content record with ID 2 also has tag bob (tag_id = 100).
Then querying all content linked to tag tag_id=100 will return both these records.
Your method getRelatedContent() works like this:
For the artist content $artist, you get all its tags (e.g., bob with tag_id=100).
You query all contents sharing any of those tag IDs excluding the artist itself.
The result includes all works tagged "bob".
Hence, artist and their works are related by the common tag, just as you expect.
Important notes:
Make sure you attach the same Tag record in the database — the exact same tag row linked in content_tags for both artist and works.
You do not create new Tag records each time with the same name, but reuse the existing one. This is crucial to making the join effective.
Your afterSave code linking tags (in the Content model) should handle this correctly (finding existing tags by name or creating if none).
How to verify:
User
object(app\models\query\ContentQuery)[149]
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_eventWildcards' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
public 'select' => null
public 'selectOption' => null
public 'distinct' => boolean false
public 'from' => null
public 'groupBy' => null
public 'join' => null
public 'having' => null
public 'union' => null
public 'withQueries' => null
public 'params' =>
array (size=0)
empty
public 'queryCacheDuration' => null
public 'queryCacheDependency' => null
public 'where' =>
array (size=2)
'template' => string 'artist' (length=6)
'status' => int 1
public 'limit' => null
public 'offset' => null
public 'orderBy' =>
array (size=1)
'title' => int 4
public 'indexBy' => null
public 'emulateExecution' => boolean false
public 'sql' => null
public 'on' => null
public 'joinWith' => null
public 'modelClass' => string 'app\models\Content' (length=18)
public 'with' =>
array (size=1)
0 => string 'tags' (length=4)
public 'asArray' => null
public 'multiple' => null
public 'primaryModel' => null
public 'link' => null
public 'via' => null
public 'inverseOf' => null
private 'viaMap' (yii\db\ActiveQuery) => null
so i dont see any related content on the page
Assistant
From the debug dump you posted, your $artistQuery looks reasonable — it’s correctly filtering template = 'artist' and status = 1, ordering by title, and eager loading tags.
If you don’t see related content ("selected works") on the page, the reasons might be:
1. artistSelectedWorks property/method on your $model is empty or not correctly implemented
You need to ensure $model->artistSelectedWorks returns related works.
For example, in your Content model:
php
public function getArtistSelectedWorks(int $limit = 3): array
{
// Use your existing getRelatedContent() method or similar logic that gets related works by tags
return $this->getRelatedContent($limit);
}
getRelatedContent() should query contents sharing tags from this content $this->tags.
Without this method or if it returns an empty array, no works will display.
2. Tags are not correctly linked between artist and works
The artist $model must have tags assigned.
The works should share those exact same tags.
Verify in DB:
Tags table should have the tag(s) assigned to both artist and works.
The content_tags join table should have rows linking artist and works to the same tag IDs.
If works are not tagged or not sharing tags with the artist, your query returns empty result.
3. The getRelatedContent() query might be incorrect or incomplete
You should confirm your getRelatedContent() method filters properly by tag IDs attached to $this->tags.
The query should exclude current artist $this->id, check content status, limit results — as in previous examples.
4. View logic displaying related content might check for wrong property or incorrectly handle empty array
Confirm your view calls $model->artistSelectedWorks, not something else.
Confirm the view handles empty arrays gracefully (no output or fallback message).
User
why cant i use:
public function getRelatedContent(int limit = 3): array
{
tagIds = array_map(fn(tag)=>tag->id, $this->tags);
code
if (empty($tagIds))
{
return [];
}
return self::find()
->joinWith(['tags' => function ($query) use ($tagIds)
{
$query->andWhere(['id' => $tagIds]);
}])
->andWhere(['<>', 'content.id', $this->id])// Exclude current content itself
->andWhere(['content.status' => 1])// Ensure published only
->distinct()
->limit($limit)
->all();
}
Assistant
You can absolutely use that method definition. The code you posted is a valid way to query related content based on shared tags. The structure is good and typical for Yii2 ActiveRecord with relations.
Explanation / Why it works:
php
public function getRelatedContent(int $limit = 3): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
return self::find()
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['id' => $tagIds]); // Filter tags by tag IDs
}])
->andWhere(['<>', 'content.id', $this->id]) // Exclude current content
->andWhere(['content.status' => 1]) // Only active contents
->distinct()
->limit($limit)
->all();
}
It gets the current content's tags ($this->tags).
If no tags, returns empty array early.
Performs a join with the tags relationship, filtering only tags with IDs in that list.
Excludes the current content.
Filters by status = 1.
Uses distinct() to avoid duplicates.
Limits by requested number.
Important details to ensure it works well:
Relation tags must be defined properly in your Content AR, like:
php
public function getTags()
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
Be sure Yii resolves table aliases correctly in your query.
The condition inside the closure:
php
$query->andWhere(['id' => $tagIds]);
Will work only if the query builder knows you mean .
User
SELECT DISTINCT testdb_content.* FROM testdb_content
LEFT JOIN testdb_content_tags ON testdb_content.id = testdb_content_tags.content_id LEFT JOIN testdb_tags ON
testdb_content_tags.tag_id = testdb_tags.id WHERE (content.id <> 5) AND (content.status=1) AND (tags.id
IN (6, 7)) LIMIT 3;
Assistant
The SQL you posted is close but it has a table alias mismatch that's causing the WHERE clause to reference incorrect table aliases, which Yii is generating because your ActiveQuery references differ from the actual aliases used.
Breakdown of the SQL you posted:
sql
SELECT DISTINCT `testdb_content`.*
FROM `testdb_content`
LEFT JOIN `testdb_content_tags` ON `testdb_content`.`id` = `testdb_content_tags`.`content_id`
LEFT JOIN `testdb_tags` ON `testdb_content_tags`.`tag_id` = `testdb_tags`.`id`
WHERE (`content`.`id` <> 5)
AND (`content`.`status` = 1)
AND (`tags`.`id` IN (6, 7))
LIMIT 3;
The problem:
Your main table is testdb_content but in WHERE clause you’re using aliases content and tags.
The query does NOT alias testdb_content as content in any explicit way, so the DB cannot recognize content.id, content.status.
Same with tags.id.
This alias mismatch leads to the query not working or returning unexpected results.
How Yii aliases tables:
When you don’t manually specify alias() in your query, Yii defaults to the full table name, e.g., testdb_content.
When you use joinWith('tags'), the relation may alias tags as tags or something else.
However, in your WHERE clause, you are filtering on alias content and tags, which may not exist in the generated SQL.
How to fix this?
1) Explicitly set alias for main query table content (recommended)
php
return self::find()
->alias('content') // set alias for content table
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['tags.id' => $tagIds]);
}])
->andWhere(['<>', 'content.id', $this->id])
->andWhere(['content.status' => 1])
->distinct()
->limit($limit)
->all();
User
public function getRelatedContent(int limit = 3): array
{
tagIds = array_map(fn(tag)=>tag->id, $this->tags);
code
if (empty($tagIds))
{
return [];
}
$query = self::find()
->joinWith(['tags' => function ($query) use ($tagIds)
{
$query->andWhere(['tags.id' => $tagIds]);// explicit alias
}])
->andWhere(['<>', 'content.id', $this->id])// Exclude current content itself
->andWhere(['content.status' => 1])// Ensure published only
->distinct()
->limit($limit);
LogHelper::debug($query->createCommand()->rawSql);// TODO
return $query->all();
}
Assistant
Your function looks good! The key fix here is ensuring that the table aliases used in your andWhere() conditions match the aliases in the actual query, and this requires explicitly aliasing the primary table in the query. Since you’re using content.id and content.status in conditions, you must tell Yii to use 'content' as the alias for your primary table.
Right now, you have:
php
$query = self::find()
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['tags.id' => $tagIds]); // explicit alias on tags
}])
->andWhere(['<>', 'content.id', $this->id]) // uses alias 'content' here
->andWhere(['content.status' => 1]) // uses alias 'content' here
->distinct()
->limit($limit);
But you did not call alias('content') on the main Content query, so Yii by default uses the full table name testdb_content (or similar) without aliasing it as content. This causes the generated SQL to have conditions:
sql
WHERE (content.id <> 5) AND (content.status=1)
but no alias content is defined, causing errors or no results.
SELECT DISTINCT content.* FROM testdb_contentcontent LEFT JOIN
testdb_content_tags ON content.id = testdb_content_tags.content_id LEFT JOIN testdb_tags ON testdb_content_tags.tag_id =
testdb_tags.id WHERE (content.id <> 5) AND (content.status=1) AND (tags.id IN (6, 7)) LIMIT 3;
Assistant
Thanks for sharing the generated SQL!
The problem:
Your SQL query joins:
testdb_content aliased as content
testdb_content_tags
testdb_tags (without alias)
but your WHERE clause references:
sql
(`tags`.`id` IN (6,7))
while in the JOIN to tags table you did:
sql
LEFT JOIN `testdb_tags` ON `testdb_content_tags`.`tag_id` = `testdb_tags`.`id`
You did not alias testdb_tags as tags, but your WHERE expects alias tags.
Why is this happening?
Because in your PHP code, you wrote:
php
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['tags.id' => $tagIds]); // expects alias 'tags'
}])
Yii tries to alias the tags table as 'tags' by default, but if the relation or map does not specify an alias or the naming conflicts, you might not get the alias you expect.
How to fix:
Force Yii to alias the tags table to tags explicitly in your relation or in the query.
Option 1: Force alias in your joinWith closure
Add alias explicitly inside the closure for tags query:
php
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->alias('tags')->andWhere(['tags.id' => $tagIds]);
}])
So your method becomes:
php
User
public function getUrl(
?string route=null,arrayparams = [],
bool adminOverride=false,boolincludeId = true,
bool includeCategory=true,boolincludeSlug = true
): string
{
if (adminOverride && route !== null)
{
useRoute=route;
}
elseif (route === null)
{
// Infer route from type and template dynamically, if valid
// Your allowed templates per type (adjust as needed)
allowedTemplates = self::allowedTemplatesByType[this->type] ?? [];
code
if ($this->template !== null && in_array($this->template, $allowedTemplates, true))
{
$useRoute = "{$this->type}/{$this->template}";
}
else
{
// fallback generic route: e.g. 'product/view'
$useRoute = "{$this->type}/view";
}
}
else
{
// Route given but no admin override, use it directly
$useRoute = $route;
}
$defaultParams = ['id' => $this->id];
if ($includeId)
{
$defaultParams['id'] = $this->id;
}
if ($includeCategory && !empty($this->category_title))
{
$defaultParams['category'] = strtolower($this->category_title);
}
if ($includeSlug && !empty($this->slug))
{
$defaultParams['slug'] = $this->slug;
}
$finalParams = array_merge($defaultParams, $params);
return Url::to(array_merge([$useRoute], $finalParams));
}
which i figured if the route is nulll it would handle this properly
Assistant
Your logic in getUrl() mostly looks good, but there’s a subtle issue causing the URL to become ?r=1%2Fview instead of something more meaningful like product/view or article/view.
well type should be 'type' => $this->integer()->notNull()->defaultValue(1),// Post = 1, Product = 2, Catalog = 3
so that likely not gonna work properly. and if post, product, catalog was used.. their is no view for these.. view
is based from:
Thanks for the detailed explanation on your content type and routing setup.
Problem restated:
Your type column is an integer (1=Post, 2=Product, 3=Catalog).
Your $this->template is one of: 'item', 'artwork', 'article', 'exhibition', 'artist', 'catalog'.
Your controllers and their actions don’t align one-to-one with type, but instead with template (e.g. purchaseController for item, artwork, articleController for article, etc).
The URL route depends on the controller and action, which are based on template more than type.
You want getUrl() to generate URLs that route properly to the corresponding controller/action.
So you can’t just map type => string and use /product/view, /post/view, because:
Those routes don’t exist or aren’t always valid.
Routes are more tightly coupled with templates and controllers.
How to adapt your getUrl() method for your setup
You want the URL to:
Call the correct controller and action based on $this->template.
Pass the id, slug, category params as needed.
Suggested approach:
Create a map from template to route (controller/action) inside your model or config, eg:
php
public static array $templateRouteMap = [
'item' => 'purchase/item',
'artwork' => 'purchase/artwork',
'article' => 'article/view',
'exhibition' => 'exhibition/view',
'artist' => 'artist/view', // or wherever artist URLs go
'catalog' => 'catalog/view',
];
Adjust your getUrl() method:
php
User
could this not just be in the getUrl()
public static array $templateRouteMap = [
'item' => 'purchase/item',
'artwork' => 'purchase/artwork',
'article' => 'article/view',
'exhibition' => 'exhibition/view',
'artist' => 'artist/view', // or wherever artist URLs go
'catalog' => 'catalog/view',
];
Assistant
Yes, absolutely!
You can (and it’s actually a great idea to) define this $templateRouteMapinside the Content model as a static property—this way your getUrl() method can directly access the mapping and generate the correct route for any content based on its template.
Centralizes route mapping per template in the model.
Easy to maintain and extend.
Your getUrl() logic stays clean and focused.
If you add new templates or controllers, just update the map.
Usage example:
php
$model = Content::findOne(5);
echo $model->getUrl(); // automatically returns URL based on $model->template
If you want, I can help with handling admin overrides, adding full URLs, or other URL variations within this setup!
User
no i meant inside the geturl() functio
Assistant
Yes, you can absolutely define and use that $templateRouteMapdirectly inside the getUrl() method as a local static variable or local variable. This keeps the mapping scoped only to that method if you prefer it that way.
Using static keyword means the array is instantiated once and reused for later calls.
Keeps the mapping encapsulated within the function (good if it’s only used there).
Easy to maintain; doesn’t clutter the model's properties.
If you want to access this map elsewhere in the model or other parts, defining it as a class-level static property might be better.
So yes:
It’s perfectly fine and common to keep the map inside getUrl() if the mapping is only relevant there!
If you want help turning this into a full working example or further customization, just ask!
User
'content/view' does not exits! AND ITS ADMIN ONLY!!! WHY ARE YOU ADDING IT
Assistant
Got it — thanks for clarifying!
Key points:
content/view route does not exist and is admin-only in your app.
So it must never be the fallback/default route.
Your content is served only via routes based on templates and their mapped frontend controllers/actions, e.g.:
'purchase/item'
'purchase/artwork'
'article/view'
'exhibition/view'
'artist/view'
'catalog/view'
You want no accidental fallbacks to content/view.
How to fix the fallback in your getUrl() method:
Remove the fallback 'content/view'. Instead:
Either throw an error,
Or return an empty string,
Or return a sensible default route that exists (e.g. homepage or index),
Or make the fallback optional and force always to have a valid route for known templates.
Example updated code snippet:
php
User
i prefer this
elseif (route === null)
{
// Infer route from type and template dynamically, if valid
// Your allowed templates per type (adjust as needed)
allowedTemplates = self::allowedTemplatesByType[this->type] ?? [];
if we can make it work with just $this->template instead of type
Assistant
Absolutely! You can simplify your URL generation logic to use only $this->template instead of $this->type and $this->template. This approach makes sense since your routing and controllers are based on the template.
Here's how to do this:
Define your allowed templates and their corresponding routes.
Use $this->template as the core routing segment.
Have a fallback route for cases when the $this->template is missing or invalid (e.g., homepage or throw an exception).
Yes! Once you implement the getUrl() method as we discussed—using $this->template to determine the route—you can simply call $model->getUrl() anywhere to get the correct URL for that content item.
Here’s what you need to do:
Make sure your Content model includes your getUrl() method, for example:
based on the model's template, id, category_title, and slug.
Summary
Implement getUrl() as above.
Call $model->getUrl() directly.
It automatically handles routing and parameters for you.
If you need help with any particular usage or extending it (e.g., admin URLs), just ask!
User
InvalidArgumentException
No route defined for template 'artist'
Assistant
The exception InvalidArgumentException: No route defined for template 'artist' means your getUrl() method tried to generate a URL for the template 'artist', but your list of allowed templates (or route map) doesn’t include 'artist', so it throws the exception.
Why is this happening?
Because in your implementation you have something like:
php
static $allowedTemplates = [
'item',
'artwork',
'article',
'exhibition',
// 'artist' is missing here
'catalog',
];
if ($this->template !== null && in_array($this->template, $allowedTemplates, true)) {
$useRoute = "{$this->template}/view";
} else {
throw new \InvalidArgumentException("No route defined for template '{$this->template}'");
}
If the template is 'artist' but it's not in $allowedTemplates, the exception is thrown.
How to fix it
Add 'artist' (and any other missing templates) to your allowed templates list or better yet, use a route map with explicit routes:
You are doing in_array($this->template, $allowedTemplates, true) which checks if $this->template is in the values of the map (which are strings like 'purchase/item', 'article/view', etc).
But $this->template is something like 'artist', 'item', 'article', etc — i.e., it's a key in the map, not a value.
This means the condition fails — for example, 'artist' (string) is not in the values list.
How to fix:
You want to check if $this->template is a key in the map:
php
if ($this->template !== null && array_key_exists($this->template, $allowedTemplates))
{
$useRoute = $allowedTemplates[$this->template];
}
else
{
throw new InvalidArgumentException("No route defined for template '{$this->template}'");
}
Then $useRoute will set to the proper route string (purchase/item, artist/view, etc.) instead of building "artist/view" from template key + /view.
class Tags extends ActiveRecord
{
public static function tableName(): string
{
return '{{%tags}}';
}
public function rules()
{
return [
[['name', 'slug'], 'required'],
[['name', 'slug'], 'string', 'max' => 255],
[['name'], 'unique'],
[['slug'], 'unique'],
];
}
/**
* Generate slug from name automatically before validating.
*/
public function beforeValidate()
{
if (!parent::beforeValidate())
{
return false;
}
if (empty($this->slug) && !empty($this->name))
{
/**
* Yii2 Inflector provides methods to convert strings between formats,
* generate URL-friendly slugs, and pluralize or singularize words.
* Example: 'My First Post' => 'my-first-post' (slug),
*
* 'postCategory' => 'post_category' (underscore),
* 'categories' => 'category' (singularize).
*/
$this->slug = Inflector::slug($this->name);
}
return true;
}
public function getContents()
{
return $this->hasMany(Content::class, ['id' => 'content_id'])
->viaTable('{{%content_tags}}', ['tag_id' => 'id']);
}
}
what i need is to be able to query tags relate to each artist query.. so if the artist is bob, they have a
category with their name say 'bob' and than i use tag that the same.. for each of their content throughtout.. i want
to share three items of the artist on the index
This works assuming your artists' title matches exactly the tag name.
If you want to relate by artist ID or use slugs instead, you can adjust where clause accordingly.
Make sure your content_tags pivot table is set up correctly.
If you want to fetch selected works for many artists at once (e.g., on index), you'll need a more optimized approach using joins or batch queries. Happy to help with that if needed!
class m250707_011350_create_content_table extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql')
{
// @url http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
/**
* Content Category Table
* @url https://www.yiiframework.com/doc/guide/2.0/en/db-migrations#create-table
*/
$this->createTable('{{%content_category}}', [
'id' => $this->primaryKey(),
// Note: columns are nullable by default; ->null() is optional and not required unless clarifying or altering
'type' => $this->integer()->notNull()->defaultValue(1),// Post = 1, Product = 2, Catalog = 3
/**
* Added Allow Templates Column 'templates'
* @see m250707_233057_insert_allowed_templates_contentCategory_table.php
*
* $this->addColumn('{{%content_category}}', 'templates', $this->text()->defaultValue(null));
*
'templates' => $this->text()->defaultValue(null),//*/
'title' => $this->string()->notNull(),
'slug' => $this->string()->unique(),
'parent_id' => $this->integer(),
/**
* BlameableBehavior
* @url https://www.yiiframework.com/doc/api/2.0/yii-behaviors-blameablebehavior
*/
'created_by' => $this->integer()->notNull(),
'updated_by' => $this->integer(),
/**
* Timestamp/dateTime and Behavior
* @url https://www.yiiframework.com/doc/api/2.0/yii-behaviors-timestampbehavior
* @see models/User.php
*
* Use the below code with $this->datetime()
*
* TimestampBehavior::className(), 'value' => new Expression('NOW()')
*
'created_at' => $this->datetime()->notNull(),
'updated_at' => $this->datetime(),//*/
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer(),
], $tableOptions);
$this->createTable('{{%content}}', [
'id' => $this->primaryKey(),
// Note: columns are nullable by default; ->null() is optional and not required unless clarifying or altering
'type' => $this->integer()->notNull()->defaultValue(1),// Post = 1, Product = 2, Catalog = 3
'template' => $this->string(50),
'category_id' => $this->integer(),
'category_title' => $this->string()->notNull()->defaultValue('Uncategorized'),
'status' => $this->smallInteger()->notNull()->defaultValue(0),// Unread = 0, Read = 1, Important = 2
'title' => $this->string()->notNull(),
'slug' => $this->string()->unique(),
'body' => $this->text()->notNull(),
'image_header' => $this->string(2000),
'meta_description' => $this->text()->notNull(),// Cannot be null with stripe checkout
'meta_keywords' => $this->text(),
/**
* Exhibition-specific (for post_exhibition template)
*/
'start_date' => $this->integer(),
'end_date' => $this->integer(),
/**
* Product-specific fields
*/
'artist' => $this->string(),
'dimensions' => $this->string(),
'medium' => $this->string(),
'year' => $this->integer(),
// Difference between each possible solution for handling money in a database.
// @url https://lashewi.medium.com/storing-currency-values-and-float-precision-99029c1e8b71
// Amount intended to be collected by this payment. A positive integer representing how much to charge in the smallest
// currency unit (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is
// $0.50 US or equivalent in charge currency. The amount value supports up to eight digits (e.g., a value of 99999999 for
// a USD charge of $999,999.99).
'price' => $this->bigInteger(),
'hide_price' => $this->tinyInteger(1)->defaultValue(0),
'purchase_options' => $this->integer()->defaultValue(3),// Default 3 = Cart(1) + Inquire(2)
'quantity' => $this->integer(),
'product_image_one' => $this->string(2000),
'product_image_two' => $this->string(2000),
'product_image_three' => $this->string(2000),
/**
* System fields
*/
'created_by' => $this->integer()->notNull(),
'updated_by' => $this->integer(),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer(),
], $tableOptions);
explain this code
code
class Content extends ActiveRecord
{
// ... existing properties and methods ...
public function getTags(): ActiveQuery
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
/**
* Get selected works for the artist
*
* @param int $limit number of works to retrieve
* @return Content[]
*/
public function getArtistSelectedWorks(int $limit = 3): array
{
if (empty($this->title)) {
return [];
}
$tagName = trim($this->title);
$tag = Tags::findOne(['name' => $tagName]);
if (!$tag) {
return [];
}
return Content::find()
->alias('c')
->innerJoin('{{%content_tags}} ct', 'ct.content_id = c.id')
->where(['ct.tag_id' => $tag->id])
->andWhere(['!=', 'c.id', $this->id])
->andWhere(['c.status' => 1])
->limit($limit)
->all();
}
// ... other methods ...
}
Why are we going off of title? I have this in the content model
code
public function getRelatedContent(int $limit = 5): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds))
{
return [];
}
return Content::find()
->joinWith('tags t')
->andWhere(['t.id' => $tagIds])
->andWhere(['<>', 'content.id', $this->id])// exclude the current content
->distinct()
->limit($limit)
->all();
}
what is the query going based off of?
Collects IDs of tags attached to the current content.
Queries contents that are tagged by any of the same tags.
Excludes the current content itself.
Returns distinct results limited by $limit.
Works well for generic "related content by shared tags" functionality.
Each artist content has a tag that is EXACTLY the same as the artist's title (i.e. artist name).
For example, artist content with title = "Bob" must have a tag "Bob" for all their related works.
We look up the tag by the artist's title.
Then find all content items tagged with this tag (works by "Bob").
Exclude the artist content itself.
Return these as artist selected works.
This is a specific use case that relies on your app convention:
Artist content's title = Tag for that artist's name
Tags are the connecting points for works related to that artist.
How is this different from getRelatedContent()?
getRelatedContent() uses tags attached to this specific content record, whatever they are (zero or many).
getArtistSelectedWorks() uses only one tag, fetched by matching the artist’s title as the tag, i.e., a dedicated tag named after the artist.
So:
getRelatedContent() → Related by shared tags of the current content.
getArtistSelectedWorks() → Related works for the artist named by the content's title.
What query is getArtistSelectedWorks generating?
Example for artist titled "Bob":
sql
SELECT c.*
FROM content c
INNER JOIN content_tags ct ON ct.content_id = c.id
WHERE ct.tag_id = (SELECT id FROM tags WHERE name = 'Bob')
AND c.id != :current_artist_id
AND c.status = 1
LIMIT 3;
Finds all content tagged with "Bob", excluding the current artist content.
What query is getRelatedContent generating?
If current content has tags [1, 2, 3], then:
sql
SELECT DISTINCT content.*
FROM content
INNER JOIN content_tags ON content_tags.content_id = content.id
INNER JOIN tags t ON content_tags.tag_id = t.id
WHERE t.id IN (1, 2, 3) AND content.id != :current_content_id
LIMIT 5;
Finds any content sharing any tag with the current content.
Summary
Method
How it finds related content
Use case
getRelatedContent()
All content sharing any tag with the current content
Generic related content
getArtistSelectedWorks()
All works tagged with tag named exactly like artist's title
Get works for an artist
Recommendation for your artist use case
Ensure artist content's title matches the tag name for their works.
Tag works with the artist's tag name.
Then getArtistSelectedWorks() will fetch related works correctly.
If you want a more flexible approach, you could:
Add a dedicated artist_id column or a relation.
Or store artist tag slugs and reference that instead of the title for matching.
If you want, I can help you refactor your methods or queries further!
artist tag
If you want one special tag per artist (for example, a slug like "artist-bob") that you attach both to the artist content and all the works, then you can query works sharing that tag:
php
public function getArtistTag(): ?Tags
{
// For example, find the tag that identifies this artist.
// This depends on an app-specific custom logic or field.
// Could be the first tag, or a tag with a particular property, or a tag with a slug matching an artist_slug field
return $this->tags ? $this->tags[0] : null; // example fallback
}
If you give me more details on how tags are assigned to artist and works, or how you want to organize artist-work relationship, I can help you write a precise solution!
if (empty($tagIds)) return [];
If the artist content has no tags, no related works can be found, so we return an empty array early.
3. Content::find()->alias('c')
Starts a query to find records in content table, aliased as c.
Joins the pivot table content_tags (aliased as ct) on content IDs.
This lets us filter contents by their tags.
JOIN explanation:
Every content row may have multiple tags; content_tags stores (content_id, tag_id) pairs.
This join allows filtering content by tags through content_tags.
5. ->where(['ct.tag_id' => $tagIds])
Filters contents that have at least one tag ID in the artist's tag IDs.
I.e., works tagged with any of the artist's tags.
6. ->andWhere(['!=', 'c.id', $this->id])
Excludes the current content record itself (the artist content).
Useful so the artist isn't listed among "their own works".
7. ->andWhere(['c.status' => 1])
Ensures only "active" or "published" contents are returned (assuming status = 1 means active).
8. ->distinct()
Because a content may have multiple tags that overlap, DISTINCT avoids duplicate rows.
9. ->limit($limit)
Limits the number of results returned (e.g., 3 works maximum).
10. ->all()
Executes the query and returns the resulting Content ActiveRecord models as an array.
What do you get?
All content entries (artworks, posts, whatever) that are tagged with any of the artist's tags.
Excluding the artist content itself.
Only active status content.
No duplicates.
Limited to $limit number.
Important notes:
This fetches works related by tag intersection — works that share any tag that the artist content is tagged with.
If your artist contents are correctly tagged with artist-specific tags (or unique tags), this will retrieve related works for that artist.
If your tags on artist content are broad or non-specific, you may get unrelated results.
You can tweak the where condition or joins if you want stricter matching (e.g., works tagged with all artist tags), but that's more complex.
Summary:
This method finds contents related by tags to the current artist content, based on common tag IDs stored in the pivot content_tags table, returning a limited number of distinct published works linked via those tags.
If you'd like, I can help you write the exact SQL or further customize it!
public function getTags(): ActiveQuery
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id']);
}
Filters directly on tags.id matching $tagIds.
Excludes the current content by comparing content.id.
Returns distinct results.
Limit applies.
Equivalent SQL fragment (simplified):
sql
SELECT DISTINCT content.*
FROM content
LEFT JOIN content_tags ON content.id = content_tags.content_id
LEFT JOIN tags t ON content_tags.tag_id = t.id
WHERE t.id IN (...)
AND content.id != :current_id
LIMIT :limit;
Usually better when filtering only by tag_id on pivot
Slightly more overhead, joins extra tags table
Ability to filter tags attributes
Limited (only by tag_id on pivot)
Yes (can filter on tag columns via alias)
Need to add other conditions
Explicitly add status filters
Should add andWhere(['content.status'=>1]) manually
Let me know if you'd like me to help convert one to the other or write a fully optimized version!
Performance
Slightly better (fewer joins)
Slightly slower (joins tags)
Filtering/tag attributes
Only on content_tags.tag_id
Can filter/sort using tag columns
Control over joins and conditions
Full control
Limited, must work with relation
Maintenance and readability
Less readable, more manual
More readable, uses relations
My recommendation
For your use case — fetching works related to an artist via tags — the manual join on the pivot table with explicit conditions (status=1) is generally better for performance and clarity, especially if you only filter by tag IDs.
However, if you later need more complex queries involving tag attributes (e.g. tag name filtering), or if you want clearer code relying on Yii relations, switch to joinWith('tags').
Bonus: To get best of both worlds
Use joinWith('tags') with eager loading and explicit conditions, like:
This works well as a straightforward start. If performance becomes an issue (due to multiple queries for related works), you can explore caching or batch loading later.
SELECT * FROM content_tags WHERE content_id = :artist_id;
SELECT * FROM content_tags WHERE tag_id IN (/* artist's tag IDs */);
Confirm works are linked with these tags.
Additional tips:
Make sure getRelatedContent() looks like:
php
public function getRelatedContent(int $limit = 5): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
return self::find()
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['tags.id' => $tagIds]);
}])
->andWhere(['<>', 'content.id', $this->id])
->andWhere(['content.status' => 1])
->distinct()
->limit($limit)
->all();
}
Use full relation name tags in the joinWith closure, and qualify columns with table name/alias, e.g., tags.id.
If you want, you can share your getRelatedContent() method, and sample tags for an artist + works, and I can help pinpoint the issue exactly!
tags.id
Because joinWith('tags') uses the relation alias 'tags' or 't' depending on your relation settings, you might want to be explicit to avoid ambiguity if needed:
php
$query->andWhere(['tags.id' => $tagIds]);
Ensure your pivot table and linking is set up, and relevant data exists linking the tags to contents.
Potential gotchas
Aliasing confusion: If your tags relation or query uses an alias other than tags, your condition 'id' => $tagIds might not work as expected. Be explicit if unsure:
php
$query->andWhere(['tags.id' => $tagIds]);
Empty $tagIds means no related content.
If you experience empty results, check whether tags are correctly linked in DB.
Also ensure the status condition matches your desired filtering logic.
In summary:
Your method is perfectly fine. Just check table aliases and database state for tags/content_tags.
Bonus: How to debug
To debug SQL generated by Yii, add:
php
// For debugging only — log the SQL in Yii debug toolbar or console:
$query = self::find()
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['tags.id' => $tagIds]); // explicit alias
}])
->andWhere(['<>', 'content.id', $this->id])
->andWhere(['content.status' => 1])
->distinct()
->limit($limit);
\Yii::debug($query->createCommand()->rawSql);
return $query->all();
This lets you see the exact SQL query Yii generates and helps troubleshoot.
Let me know if you want me to help check your tags relation or suggest optimizations!
Then the generated SQL aliases the main content table as content, so content.id, content.status, and tags.id all make sense.
2) Alternative: Use aliases consistent with the generated query
However, using raw table names in conditions is more brittle and less portable if your DB or table prefix changes.
Summary and best practice:
Always alias your main table in the ActiveQuery if you use aliases in your conditions.
php
->alias('content')
Use matching aliases in all conditions (content.id, content.status, tags.id).
This ensures generated SQL works correctly.
Example final method:
php
public function getRelatedContent(int $limit = 3): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
return self::find()
->alias('content')
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->andWhere(['tags.id' => $tagIds]);
}])
->andWhere(['<>', 'content.id', $this->id])
->andWhere(['content.status' => 1])
->distinct()
->limit($limit)
->all();
}
With this, your SQL would look something like:
sql
SELECT DISTINCT `content`.*
FROM `testdb_content` `content`
LEFT JOIN `testdb_content_tags` ON `content`.`id` = `testdb_content_tags`.`content_id`
LEFT JOIN `testdb_tags` `tags` ON `testdb_content_tags`.`tag_id` = `tags`.`id`
WHERE (`content`.`id` <> 5)
AND (`content`.`status` = 1)
AND (`tags`.`id` IN (6,7))
LIMIT 3;
This works correctly because table aliases match the ones used in the WHERE.
If you want, I can help you with any other query or ActiveRecord fine-tuning!
Always set alias explicitly if you use table aliases in your conditions to avoid mismatch.
Use the same alias in all your conditions/predicates.
The logging will help you see the actual SQL Yii builds — confirm the aliases are correct.
If results are still empty, verify:
$tagIds contain valid tag IDs.
The pivot table links contents and tags correctly.
Related content exists matching those tags.
Happy to help with that too — just ask!
public function getRelatedContent(int $limit = 3): array
{
$tagIds = array_map(fn($tag) => $tag->id, $this->tags);
if (empty($tagIds)) {
return [];
}
$query = self::find()
->alias('content')
->joinWith(['tags' => function ($query) use ($tagIds) {
$query->alias('tags')->andWhere(['tags.id' => $tagIds]);
}])
->andWhere(['<>', 'content.id', $this->id])
->andWhere(['content.status' => 1])
->distinct()
->limit($limit);
LogHelper::debug($query->createCommand()->rawSql);
return $query->all();
}
With this, Yii will generate:
sql
LEFT JOIN `testdb_tags` `tags` ON ...
and WHERE tags.id IN (...) will work correctly.
Option 2: Modify your relation to specify alias for tags
In your Content model, your getTags() relation could specify alias like this:
php
public function getTags()
{
return $this->hasMany(Tags::class, ['id' => 'tag_id'])
->viaTable('{{%content_tags}}', ['content_id' => 'id'])
->alias('tags'); // explicitly define alias here
}
This way joinWith('tags') will ALWAYS alias the tags table as tags.
Why aliasing matters:
SQL requires you to use the alias defined in the JOIN in all places (SELECT, WHERE, ORDER BY).
Mismatched alias in WHERE causes database errors or empty results.
TL;DR:
Add ->alias('tags') when building the join query OR in the relation.
This ensures your WHERE clause referencing tags.id is valid.
This will fix your SQL and should return expected results.
If you want, I can help you double-check your relation and the full usage.
Instead of '1/view', you get 'post/view' (if type=1).
Your route URLs become meaningful and readable.
URLs like /post/view?id=5&category=idm&slug=what-about-me instead of /1/view?....
Bonus: Where does $allowedTemplatesByType come from?
Make sure your $allowedTemplatesByType uses string route segment keys consistent with this mapping:
php
protected static array $allowedTemplatesByType = [
1 => ['view', 'special'], // for "post" type = 1
2 => ['view', 'catalog'], // for "product" type = 2
// etc...
];
Summary
Your type is numeric, but your route expects strings such as post, product as first segment in the URL path. Map your numeric type to string route prefixes before building the URL route segment.
If you want I can help you build a fully working example!
If no route is provided, $useRoute is set based on $this->template using your mapping.
The default fallback route is 'content/view' if the template isn’t found in the map.
This gives you fine control over which controller/action handles which template.
You keep flexibility to override or include/exclude ID, category, slug parameters.
How to maintain your map:
Update $templateRouteMap if you add new templates or controllers.
This keeps routing logic centralized and easy to adjust.
Optional: Handle index vs view routes if needed
If you want to generate index URLs sometimes, you could add a parameter or extend the map to support different actions, but for content detail URLs, usually view or custom action like item works.
Summary
Your type is an internal classification — mostly irrelevant to URL routes.
Use your template to determine correct controller/action route.
Map templates to actual controller/action routes explicitly.
getUrl() returns a route using that map + params like id, slug, category.
If you want, I can help you write a helper to generate URLs for any template, including index vs view, or admin URLs with override!
public function getUrl(
?string $route = null,
array $params = [],
bool $adminOverride = false,
bool $includeId = true,
bool $includeCategory = true,
bool $includeSlug = true
): string {
static $templateRouteMap = [
'item' => 'purchase/item',
'artwork' => 'purchase/artwork',
'article' => 'article/view',
'exhibition' => 'exhibition/view',
'artist' => 'artist/view',
'catalog' => 'catalog/view',
];
if ($adminOverride && $route !== null) {
$useRoute = $route;
} elseif ($route === null) {
if (isset($templateRouteMap[$this->template])) {
$useRoute = $templateRouteMap[$this->template];
} else {
// No matching route for this template — handle this explicitly:
// Option 1: throw Exception
throw new \InvalidArgumentException("No route defined for template '{$this->template}'");
// Option 2: return empty string (no URL)
// return '';
// Option 3: fallback to homepage or some known safe route
// $useRoute = 'site/index';
}
} else {
$useRoute = $route;
}
$defaultParams = [];
if ($includeId) {
$defaultParams['id'] = $this->id;
}
if ($includeCategory && !empty($this->category_title)) {
$defaultParams['category'] = strtolower($this->category_title);
}
if ($includeSlug && !empty($this->slug)) {
$defaultParams['slug'] = $this->slug;
}
$finalParams = array_merge($defaultParams, $params);
return Url::to(array_merge([$useRoute], $finalParams));
}
Why this is better:
You never generate invalid or admin-only routes by accident.
You catch misconfigurations early via exception (or your preferred fallback).
Keeps your frontend URLs clean and aligned with existing controllers/actions.
Summary:
Remove 'content/view' fallback from getUrl()!
Add explicit handling of unknown templates (throw, empty, redirect).
Always map known templates to correct frontend routes.
If you want help improving your URL map or gracefully handling missing templates, I’m happy to assist.
Explanation:
This assumes you have controllers named exactly after $template, e.g.:
ArticleController with actionView()
ExhibitionController with actionView()
etc.
URL format will be: template/view?id=xxx&category=yyy&slug=zzz
The method throws an exception if the template is missing or invalid. You can adjust that behavior.
Optional improvements
If some templates use different actions (like item and artwork using purchase controller), you could extend into a map:
$work->getUrl() builds URL for that specific work content.
$model (the artist) generates URL for that artist.
Calling $model->getUrl($work->template) mixes the URL generation - it's generating a URL for the artist but passing a different route string (the template key of the work) — but URL parameters (like id, slug) still come from artist, so URL is for the artist but route is the work route, which can cause conflicts.