L
L
lynnikvadim2015-11-10 07:35:25
Laravel
lynnikvadim, 2015-11-10 07:35:25

How to get records from database in Laravel?

There is a table post in which there is a cell "category".
This cell contains post categories. They look like "Architecture;Construction;Installation"
How can I make a selection of all posts that have the "Construction" category?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
6
65536, 2015-11-10
@lynnikvadim

There is a table post in which there is a cell "category".
This cell contains post categories. Have the form "Architecture;Construction;Installation"

this is generally wrong. you should have 2 tables linked by a 1-to-many relationship.
class Post extends Eloquent
{
    public $table = 'posts';

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

class Category extends Eloquent
{
    public $table = 'categories';

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

then you can beautifully rake out the necessary posts, for example, such a construction will return a collection of post models in the category such and such
if you need to apply sorting or a condition, then you need to call it as a method
also in reverse order, you can get the category of the model for the post of such and such, for example, with such and such an id,
create a post in such and such a category
etc. read the documentation better, everything is as simple as 3 kopecks

M
Mokhirjon Naimov, 2015-11-10
@zvermafia

Will it fit?:
PostModel::whereCategory('Строительство')->get();

X
xmoonlight, 2015-11-10
@xmoonlight

laravel.com/docs/5.1/queries#selects

A
Arman, 2015-11-10
@Arik

With such a database architecture, there are three questions:
1. How to correctly query the database?
2. How to make this request through Laravel?
3. How to do it using Laravel models, here Models\Post?
1. If there is no way to change the database architecture, then I would use a regular expression in the database, something like:
2/3. Smoke docs:
laravel.com/docs/5.1/database
laravel.com/docs/5.1/eloquent

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question