class Cart extends ActiveRecord
{
public function getContentProduct(): ContentQuery
{
return $this->hasOne(Content::class, ['id' => 'product_id']);
}
}
then to call it in another file be?
product=cart->content_product;
Assistant
Yes, that is correct.
Given your getter method defined as:
php
class Cart extends ActiveRecord
{
public function getContentProduct(): ContentQuery
{
return $this->hasOne(Content::class, ['id' => 'product_id']);
}
}
You can access the related Content model instance using the magic property like this:
php
$product = $cart->contentProduct;
Important: In Yii2, when you define a relation method getContentProduct(), the corresponding property name to access the relation is camelCase without the "get" prefix, which means $cart->contentProduct — not$cart->content_product.
So the correct way is:
php
$product = $cart->contentProduct;
If you try $cart->content_product, Yii will not convert underscore format for you automatically in this context.
Summary:
Relation method: getContentProduct()
Access property: $cart->contentProduct
NOT: $cart->content_product
If you want to access it using snake_case like $cart->content_product, you'd have to define a magic method or a property yourself, but by default Yii uses camelCase based on the method name.
User
public function getCartItems(): array
{
$this->checkInventory();
Database Exception – yii\db\Exception
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'c.type' in 'where clause'
The SQL being executed was: SELECT * FROM ldlite_cartc WHERE (c.type=2) AND (c.created_by=1)
↵
Caused by: PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'c.type' in 'where clause'
// TODO Get all cart items for this user with product eager loaded
cartItems=Cart::find()−>alias(′c′)−this->_userId
])
->all();
Assistant
The error
code
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'c.type' in 'where clause'
means that the column type does not exist in the table aliased as c (which is ldlite_cart).
What is most likely going on:
You have aliased the Cart table as c (->alias('c')).
Your query tries to filter on c.type.
But the ldlite_cart table does NOT have a column named type.
Check your database schema for ldlite_cart. If type column is not in the cart table, then that where condition referencing c.type is invalid and causes the error.
Possible causes & fixes:
1. The type column belongs to the related table (e.g. content), not the cart table
If type belongs to the related table (maybe in the content table), but you add the condition to the cart query, it fails.
If so, you can:
Remove c.type condition from the main query.
Add the condition inside the related model query (content relation).
Example: Add type filter in the relation:
php
// In Cart.php
public function getContent(): ContentQuery
{
return $this->hasOne(Content::class, ['id' => 'product_id'])
->andWhere(['type' => ContentCategory::TYPE_PRODUCT]);
}
// Then your query becomes:
$cartItems = Cart::find()
->alias('c')
->with('content') // eager load
->where(['c.created_by' => $this->_userId])
->all();
2. If type is supposed to be in cart table
Make sure type column exists in the ldlite_cart table.
If it has a different name or is missing, adjust accordingly.
User
oh i was trying to check content for type
Assistant
Exactly!
If you want to filter by type in the content table, not in the cart table, then your where() condition on c.type is invalid because c is cart.
How to fix it:
You have two options:
Option 1: Filter in the relation definition (getContent())
php
public function getContent(): ContentQuery
{
return $this->hasOne(Content::class, ['id' => 'product_id'])
->andWhere(['type' => ContentCategory::TYPE_PRODUCT]);
}
Now every time you eager load or access $cart->content, only content rows with that type will be matched.
Your query then can simply be:
php
$cartItems = Cart::find()
->alias('c')
->with('content') // eager load content with the filtered condition inside relation
->where(['c.created_by' => $this->_userId])
->all();
Option 2: Join with content and filter in the where() clause
This will generate a SQL JOIN and filter cart items that have content of that type.
Important:
Use innerJoinWith() if you want only carts that have a related content matching the condition.
Use leftJoinWith() if you want carts regardless whether related content exists or matches.
If you want, I can help you write a full example!
User
im doing this now
public function getContent(): ContentQuery
{
return $this->hasOne(Content::class, ['id' => 'product_id'])
->andWhere(['type' => ContentCategory::TYPE_PRODUCT]);
}
Assistant
Yes, that’s perfectly fine and actually a good approach!
By adding the condition inside the relation method:
php
public function getContent(): ContentQuery
{
return $this->hasOne(Content::class, ['id' => 'product_id'])
->andWhere(['type' => ContentCategory::TYPE_PRODUCT]);
}
You ensure that whenever you access $cart->content or eager load it with with('content'), it only fetches the related Content record where type equals ContentCategory::TYPE_PRODUCT.
What this means:
If a cart item’s related content has a different type, $cart->content will be null.
When you do $cartItems = Cart::find()->with('content')->all(), Yii will automatically include this condition for the eager loading query.
So your filtering on content's type is enforced at the relation level.
Just a couple of tips:
Make sure ContentCategory::TYPE_PRODUCT is the correct constant/value.
If you want to get only carts that have that content (i.e., exclude carts without such content), consider joining (via innerJoinWith('content')) or filtering carts by content existence.
public function ofTemplate(string|array $template): static
{
return $this->andWhere(['template' => $template]);
}
whenever i use ofTemplate..
Assistant
The issue likely comes from how the ofTemplate() scope works with the 'template' column and the argument you pass. Here are some things to check and suggestions to fix it:
1. Check the database column type and value
Is the template column in your content table a string or something else (e.g., JSON, serialized array)?
Does the value stored match exactly the values you pass to ofTemplate()?
For example:
id
template
1
artwork
2
blog
If so, andWhere(['template' => $template]) with $template = 'artwork' should work fine.
2. Passing an array to andWhere on an equality condition
Your method is declared as:
php
public function ofTemplate(string|array $template): static
{
return $this->andWhere(['template' => $template]);
}
If you call:
php
->ofTemplate(['artwork'])
Then ['template' => ['artwork']] will become an IN condition:
sql
template IN ('artwork')
which is fine — basically same as template = 'artwork'.
But if you call:
php
->ofTemplate('artwork')
then it is
sql
template = 'artwork'
which is also fine.
3. Confirm $model = Content::find() is a ContentQuery instance
Make sure your find() returns the custom query class that includes these scopes.
4. Check if other scopes like titleLike() might filter out all results
Sometimes combined scopes cause no result.
Try this to debug:
php
User
public function titleLike(string term): static
{
return this->andWhere(['like', 'title', $term]);
}
works fine
Assistant
Thanks for confirming titleLike() works fine!
Since titleLike() works but ofTemplate() makes the query return null, this strongly suggests the problem is with the condition inside ofTemplate(), or the values in your database for the template column.
Step-by-step checklist to troubleshoot ofTemplate():
1. Confirm the template column exists and contains values you expect
Run this SQL directly in your database:
sql
SELECT DISTINCT template FROM content;
Do you see 'artwork' in the results?
Are the values exactly 'artwork' or something else (e.g. uppercase, with trailing spaces)?
If it’s not exact, your equality match (andWhere(['template' => 'artwork'])) will not return results.
If this returns your record, your scopes are correct.
Conclusion:
Your scopes look fine, and combined with the model data you posted, the query should return a result — assuming the title and other conditions match.
If your original query combining titleLike('la fish'), ofTemplate('artwork'), and published() returns null, the mismatch is likely in titleLike('la fish') — the title in the DB is artwork-test-3 which probably does not contain 'la fish'.
Summary:
ofTemplate() works fine.
published() works fine.
The title probably doesn't match 'la fish'.
Adjust or test each condition separately to isolate which one excludes your record.
If you want an exact query to find your example record (title='artwork-test-3'), try:
You showed ActiveForm::begin(), but no ActiveForm::end(). Make sure you close the form:
php
ActiveForm::end();
Without this, the form won't close properly and may not submit as expected.
User
public function actionAdd(): Response
{
// CartAddForm requires productIdandquantity
$model = new CartAddForm();
code
$session = \Yii::$app->session;
$request = \Yii::$app->request;
if (($request->isPost) && ($model->load($request->post()) && $model->validate()))
{
$product = Content::find()->id($model->productId)->ofType('product')->one();
if (!$product)
{
throw new YiiWebNotFoundHttpException(\Yii::t('app', 'Item not found.'));
}
// Ensure session is ready
$this->ensureSessionReady();
if ($this->_isGuest)
{
// addItem(int $productId, int $quantity): bool
$added = $this->_sessionCart->addItem($product->id, $model->quantity);
}
else
{
// addItem(int $productId, int $quantity, bool $createIfNotExists = false): bool
$added = $this->_userCart->addItem($product->id, $model->quantity, true);
}
if ($added)
{
$session->setFlash(
'success',
\Yii::t('app', 'Added `{title}` to your purchase list.', ['title' => $product->title])
);
}
else
{
$session->setFlash(
'error',
\Yii::t('app', 'Could not add `{title}` to your purchase list.', ['title' => $product->title])
);
}
// Redirect back to the referring page or fallback to homepage
return $this->redirect($request->referrer ?: ['site/index']);
}
// Handle invalid post or no post, maybe redirect to homepage
return $this->redirect(['site/index']);
}
im always redirected to the site/index
Assistant
Thanks for sharing your controller action. Based on your description:
I am always redirected to the site/index (i.e., the final redirect in your method), which means the condition if (($request->isPost) && ($model->load($request->post()) && $model->validate())) is not passing.
Why might that be?
$request->isPost is false:
Possibly your form is not submitting via POST.
$model->load($request->post()) returns false:
The POST data is not structured correctly for your model.
$model->validate() returns false:
The form data is invalid per your model rules.
Let's diagnose step by step.
Step 1: Check form submission method and data
In your view:
You set 'method' => 'post' in ActiveForm, so it should submit by POST.
Check browser dev tools -> Network tab -> on submit, inspect request method and payload.
If it returns a model, then your ofTemplate() works but something else is filtering it out.
If not, check your database column values for template.
If you want, share your table schema or sample data of the template column and relevant scope definitions (titleLike(), published()) and I can help pinpoint the issue!
public function actionAdd($id)
{
$model = new CartItemForm(); // Or relevant model for form (not Content directly)
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// Use $id and $model->quantity to add to cart...
} else {
// Either validation fails or GET method, render form or return error
}
}
4. The quantity max attribute
'max' => $model->quantity, is that intentional? Usually, quantity field max is the maximum allowed quantity to order.
If $model->quantity is the current stock, that makes sense — but be sure the value is set correctly and non-zero.
5. Form CSS & Bootstrap classes
The use of Bootstrap classes looks OK, but to debug, temporarily remove custom classes and see if basic form submission works.
6. JavaScript interference
Check browser console for JS errors.
Check if any JS validation (e.g., client validation) is preventing submit.
Try disabling JS to see if form submits.
7. CSRF token
ActiveForm should automatically add CSRF token hidden input. Make sure the CSRF meta tag is present in your layout:
php
<?php $this->registerCsrfMetaTags() ?>
Without CSRF, POST requests may be rejected.
Summary checklist:
Add ActiveForm::end(); after your form inputs and submit button.
Verify generated HTML (especially form tag, input name).
Check your controller action accepts and processes data properly.
Ensure CSRF meta tags present and token submitted.
Test submit, watch network tab for form POST and response.