Exploring data retrieval through relationships in the Yii PHP framework

Greetings, I am facing an issue with my database where I utilize a link table to establish connections between products and categories.

The relational structure is as follows:

Product      ProductCategories       Category
Id           Id                      Id
Name         ProductId               Name   
             CategoryId 

Therefore, the productCategory table serves the purpose of linking Products to Categories.

My current challenge revolves around retrieving all Products categorized under the category with the ID of 1.

I have attempted the following code to achieve this but unfortunately, it does not appear to be functioning correctly:

$models = Products::model()->with('productcategories')->findByPk(1);

Below are the relationships defined within the Products model:


public function relations()
{
    return array(
        'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
    );
}

Answer №1

function establishRelations()
{
    return array(
        'productCategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
        'RelatedCategories' => array(self::HAS_MANY, 'Category', '',
            'through'=>'productCategories',
            'on' => 'Categories.Id = productCategories.CategoryId',
        ),
    );
}

// Retrieve all Products associated with a Category having id = 1
$result = Products::model()->with('RelatedCategories')->findAll('Categories.Id = 1');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are all properties in PHP's mysql_fetch_object function converted to strings?

Looking for assistance! I'm facing an issue where mysql_fetch_object is returning all properties as type string. I need to convert the object to JSON while preserving numerical and Boolean values. The parsing of resulting JSON is taking a long time ...

Is it possible to convert Google Books API data into a PHP array?

Upon querying Google, I received the resulting information: { "kind": "books#volumes", "totalItems": 1, "items": [ { "kind": "books#volume", "id": "t9S82uKGp8IC", "etag": "rn9INXAtx88", "selfLink": "https://www.googleapis.com/books/v1/v ...

Blank page received upon submission of Laravel Select2 application

I'm experiencing an issue with submitting a form using select2. After submission, I receive a completely blank page. I'm not sure why the controller is not working properly. All I need is to send the store id. <form id='filter' act ...

Show the result of (Firstname) on the thank you page after the form has been submitted

Need help with a PHP issue; it seems simple but I'm uncertain of the correct method, whether through jQuery or PHP. I have a contact form where I want certain field results to display on the thank you page after submitting the form: Thank you for en ...

Show the precise selection from one dropdown menu based on the chosen value in another dropdown menu

How can I retrieve the scheduleID value from a specific MovieID value within a comboBox? Movie Selection Box: <?php $query = "select * from ref_movies ORDER BY MovieID"; $result = mysql_query($query) or die (mysql_error()); echo '<s ...

The integration between curl_exec and Mailchimp fails to function properly when implemented with AJAX

I have successfully set up a form within my Wordpress site to send data to Mailchimp using their API. When I use a standard form that redirects to a designated page, everything works smoothly and all the data gets imported as expected. However, I am now t ...

The suggestions for auto-complete in jQuery are not showing up as expected

I am looking to implement a feature where suggestions from the database are automatically populated in a text box as I type. Additionally, when I select a suggestion, other related text fields should be filled automatically. Below is the code snippet: Vi ...

php The setcookie function is not functioning properly

Here are the contents of my test files: File test.php: <?php setcookie("test", "test", time() + 3600); header("Location:test2.php"); File test2.php: <?php if(!isset($_COOKIE['test'])) { echo 'cookie not set'; } else { ...

Obtain JSON data from an array

I am currently using the Slim framework to create a REST API. In my code, the route for tasks is defined as follows: $app->get('/tasks', 'authenticate', function() { global $user_id; $response = array(); $items = array() ...

Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format no ...

In my PHP project, I am working on implementing a feature that will display the name of the logged-in user on the website, such as "Hello Mike" or "Welcome Mike"

When a user is logged into my website, I want it to display a greeting like "Hello" or "Welcome User." This is the code I am currently using: <?php $user = $_GET['session_is_registered']; echo ('$user'); ?> However, the PHP c ...

The foreach statement in PHP is functioning correctly, however, the message in the else statement is

I have been working on fetching data from my model as an array and using a php foreach loop to display it in a specific view. I am now trying to implement an additional layer of logic to only display certain bookmark_ids. Even though the data is being dis ...

Retrieving intricate JSON data from a specific web address

I need assistance in extracting and printing the date value from the JSON content available at the specified URL. Specifically, I am looking to retrieve the date value of "data.content.containers.container.locationDateTime" only if the "data.content.conta ...

Using PHP to send JSONP callback responses

Is it possible to achieve "two-way" communication using JSONP and PHP? For example: jQuery / JSONP $.ajax({ url: 'http://server/po.php', cache : false, dataType: 'jsonp', timeout: 30000, type: 'GET', ...

Tips for compressing multiple images into a single file using php after they have been downloaded

I have a PHP code that downloads multiple images from private websites. My goal is to place all these images into a zip file. How can I achieve this? <?php $num = $_POST['num']; for ($i=1; $i <= $num ; $i++) { $url_to_image = $_POST ...

Trouble with Spaces in FPDF PHP Library on UNIX Operating System?"

I have encountered a strange issue while using the FPDF library to create a PDF document from MySQL tables. Everything works perfectly fine on my Windows computer, but when I try running the script on my Ubuntu machine, all the spaces disappear inexplicabl ...

Is the dataType: "json" parameter necessary in AJAX requests under certain conditions?

Upon observation, it appears that there is no need to include dataType: "json" in our AJAX request when the server file is already structured in .json format. index.html $.ajax({ url: "ajax/test.json", data: "id="+id, cache: false, type: ...

PHP is unable to establish a connection with the Xdebug client within the Docker environment

Recently, I encountered a perplexing issue while using WSL2 with docker-ce installed, running PHP 8 and Xdebug 3. Despite numerous attempts at debugging, it appears that PHP is unable to connect to the Xdebug client for unknown reasons. Surprisingly, when ...

Adding a prefix to a Smarty variable

Seeking a solution to add a string in front of a Smarty variable. A dynamic form has element names like input-1 (where 1 represents the id of the setting/field). I attempted to use {capture}{/capture}, but it seems to only work the first time due to the f ...

What is the best way to set the proper x-axis format for a chart in phpspreadsheet?

Currently, I am using 33_Chart_create_scatter.php to generate a two-line xyScatter chart. Everything seems to be going smoothly, except for the formatting of the x-axis which is not as desired. Despite no associated errors, the x-axis appears subpar as sho ...