This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

kuroski
kuroski

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

Daniel81
Daniel81

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 %}
kuroski
kuroski

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 >_<

Daniel81
Daniel81

@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

Blackpig Creative
Blackpig Creative

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

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.