douduan7295 2017-11-21 12:30
浏览 97
已采纳

laravel模型中的自定义路径

I have 2 model in laravel 5.5

Article.php class with 2 function:

public function sluggable()
{
    return [
        'slug' => [
            'source' => 'title'
        ]
    ];
}

public function path()
{
    return "/$this->slug";
}

Category.php

public function childs() {
      return $this->hasMany('App\Category','parent_id','id') ;
}

categories table:

id /  article_id  / parent_id / name

Now for example,for this code in view: {{ $article->path() }}

it prints:  `example.com/article_slug`

But I want simething like this:

example.com/parentCategory/subCategory-1/.../subCategory-n/article_slug

How can I do it in path() function? Is it possible?

  • 写回答

2条回答 默认 最新

  • douxian7808 2017-11-21 13:15
    关注

    I'm assuming your question is asking how you can generate uri's for categories that can have an unlimited amount of children via their slugs.

    How I would go about tackling something like this is by using a hierarchical data pattern within MySQL which will allow you to get a list of descendants / ancestors by performing one query. There are numerous ways to implement this, but for the purpose of this explanation I'm going to explain how to do it using the nested set pattern. More specifically, I'll be giving demonstrating how to do this using lazychaser's nested set package.

    Categories Table Migration

    use Kalnoy\Nestedset\NestedSet;
    
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        NestedSet::columns($table);
        $table->timestamps();
    });
    

    The nested set columns will add _lft, _rgt, and parent_id columns to your table. I would recommend you do some research on how the nested set model works in order to understand what the left and right columns are used for.

    Category Model

    use Kalnoy\Nestedset\NodeTrait;
    
    class Category extends Model
    {
        use NodeTrait;
    
        //
    }
    

    Now you can create a child category like so:

    $parentCategory = Category::first();
    
    $parentCategory->children()->create([
        'name' => 'Example Category'
    ]);
    

    This means that on a deeply nested category you can do:

    $categories = Category::ancestorsAndSelf($article->category_id);
    

    This will return all ancestors of the above category, then to get the uri you can do something like:

    $uri = $categories->pluck('slug')->implode('/') . '/' . $article->slug;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?