检查是否存在并创建

时间:2017-12-07 14:25:44

标签: php laravel laravel-5

我尝试在DB中为标题生成并保存uncial slug。

                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);

如何检查网址中是否存在此类字段?如果存在,请保存:

'url' => str_slug($feed->name,"-1"),

我想:

  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE, 
            };
            break;

但是它不干净,如果这样的网址 - str_slug($feed->name,"-1")已经存在怎么办?

3 个答案:

答案 0 :(得分:1)

您可以使用:

$friendlyUrl = friendlyUrl::firstOrNew(
    ['url' => str_slug($feed->name,"-1")], [
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,]
);

$friendlyUrl->save();

答案 1 :(得分:0)

试试这个 -

$FriendlyUrl = FriendlyUrl::firstOrNew(array('url' => str_slug($feed->name)));
$FriendlyUrl->action = "feeds/{$feed->id}";
$FriendlyUrl->complicated = false;
$FriendlyUrl->page_type_id = PageType::TYPE_INDIVIDUAL_FEED_PAGE;
$FriendlyUrl->save();

参考 - Insert a new record if not exist and update if exist, laravel eloquent

答案 2 :(得分:0)

标题的独特标题

public static function boot()
           {
               parent::boot();

           static::creating(function($model) {
               $model->slug = str_slug($model->ToBeSluggified);// change the ToBeSluggiefied

               $latestSlug =
                   static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
                       ->latest('id')
                       ->value('slug');
               if ($latestSlug) {
                   $pieces = explode('-', $latestSlug);

                   $number = intval(end($pieces));

                   $model->slug .= '-' . ($number + 1);
               }
           });
       }