Please pardon me if this is an ignorant question. I’m a self-taught developer with some experience but I’m only a year into using Yii, and Yii1, at that.
It’s possible I’ve made SQL mistakes as well.
I’m trying to make a widget for a site. The widget shows a randomly chosen song and allows the user to play it in an audio player. The randomly chosen song data includes fields from two joined tables.
At first, I tried to pass the values into the widget with a findBySql
, like this:
$nowplaying = Catalog::model()->findBySql(
"SELECT c.Title, c.Artist, tr.audioUrl, tr.fk_copyright
FROM Catalog c
JOIN Tracks tr
ON c.pk = tr.fk_Catalog
WHERE tr.audioUrl IS NOT NULL
ORDER BY RAND()
LIMIT 1");
In that case, the values from the Catalog table displayed correctly, but the values from the joined table, Tracks, don’t show up at all. In a var_dump
they also don’t appear. But if I run this SQL query in Sequel Pro, I get the expected values, from both tables.
So, I tried again. I learned about the Query Builder in Yii, and created a different method for fetching the data from joined tables, like this:
$nowplaying = Yii::app()->db->createCommand()
->select('c.Title, c.Artist, tr.audioUrl, tr.fk_copyright')
->from('Catalog c')
->join('Tracks tr', 'c.pk=tr.fk_Catalog')
->where('audioUrl IS NOT NULL')
->order('RAND()')
->limit(1)
->queryRow();
In this case the var_dump
gives me all the correct data, but nothing shows up in the widget!
the widget code is long, but here’s an excerpt with some example data:
<b><?php echo $nowplaying->Title?></b>
<b><?php echo $nowplaying->Artist?></b>
<audio id="audioSrc" src="<?php echo $nowplaying->audioUrl ?>"></audio>
<div class="audio-credits">
<?php if ($nowplaying->fk_copyright == 1): ?>
SHOW CREDIT
<?php else: ?>
DON'T SHOW CREDIT
<?php endif?>
</div>
So, I have two questions:
- In my first query, why did I only get values from the first table in the join?
- In my query that worked,
var_dump
showing all requested values from both joined tables, why did nothing show up in my widget?
I guess there’s a third question: 3. Is one of these methods better than the other? And should I even be using a widget? Would RenderPartial be better?
To conclude, I don’t know if this is an issue of me not knowing Yii, or me not knowing SQL. I’m happy to be shown my mistakes, either way.