Laravel侦察员检查关系是否为空?

时间:2017-07-27 10:04:06

标签: laravel laravel-5 algolia laravel-scout

命名空间App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Event extends Model
{
    protected $table = 'events';
    public $timestamps = true;

    use Searchable;
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    public function entities()
    {
        return $this->belongsTo('App\Entity', 'entity_id');
    }
    public function users()
    {
        return $this->belongsTo('App\User', 'id');
    }
    public function events()
    {
        return $this->belongsTo('App\DirtyEvent', 'id');
    }
    public function toSearchableArray()
    {
        $data = $this->toArray();
        $data['entities'] = $this->entities->toArray();
        return $data;
    }
}

这是我的事件模型,你可以看到我正在使用toSearchableArray这是Laravel scout函数来导入'关系'到algolia。然而问题是有时它是空的。例如,

  

事件ID 1具有entity_id 1

但在另一个例子中

  

事件ID 2具有entity_id = null

如何将这个函数修改为在将它放入数组之前检查entity()关系是否为空?

3 个答案:

答案 0 :(得分:1)

如果我理解你的话,这应该会有所帮助。如果关系不存在则返回一个空数组,而scout将不会更新索引

  public interface IShape
        {
          // Defines the prototype(template) 
            void Draw();
        }


  // All the sub classes follow the same template but implementation can be different.

    public class Circle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("This is a Circle");
        }
    }

    public class Rectangle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("This is a Rectangle");
        }
    }

答案 1 :(得分:0)

请更新foreign_key作为此 user_id为foreign_key而不是id
event_id为foreign_key而不是id

public function users()
{
    return $this->belongsTo('App\User', 'user_id');
}
public function events()
{
    return $this->belongsTo('App\DirtyEvent', 'event_id');
}

答案 2 :(得分:0)

我认为如果在toArray()之前加载关系。

public function toSearchableArray()
{
    $this->entities;

    return $this->toArray();
}