This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Good evening.
I wonder if someone could guide me in this situation.
I am creating a plugin, and it has a model class, in which it can have a image or not.
How I run the query to list all the records that have an image...
Ex:
-- myPlugin/models/MyModel.php
class MyModel extends Model
{
...
public $attachOne = [
'image' => ['System\Models\File']
];
}
-- myPlugin/components/MyComponentController.php
class MyComponentController extends ComponentBase
{
protected function listSlides()
{
$records = MyModel::magicQueryThatSolveMyProblem();
return $records;
}
}
-- myPlugin/components/mycomponent/default.htm
{% for record in records %}
<p>
<img src="{{record.image.getPath()}}" />
</p>
{% else %}
<p class="no-data">No images</[>
{% endfor %}
Last updated
Try:
{% for record in records %}
{% if record.image %}
<p><img src="{{record.image.getPath()}}" /></p>
{% else %}
<p class="no-data">No images</p>
{% endif %}
{% endfor %}
Thanks for the reply ^^ . I will end up doing this way. The problem is that I list all records, even those who have no picture, so it's kind of "inefficient".
But Thanks a lot >_<
@kuroski
You can just take out the {% else %}
statement, then it will only display records the DO have an image:
{% for record in records %}
{% if record.image %}
<p><img src="{{record.image.getPath()}}" /></p>
{% endif %}
{% endfor %}
Last updated
It would be better to return just the records that have an image from the db.
Have a look at adding a scope to your model - Eloquent Query Scopes
Something like this maybe
-- in your model --
public function scopeWithimage($query)
{
return $query->whereNotNull('image');
}
-- in your controller --
$records = MyModel::withimage()->get()
1-5 of 5