代码之家  ›  专栏  ›  技术社区  ›  diego

拉威尔雄辩地选择1:n到1:1

  •  1
  • diego  · 技术社区  · 7 年前

    我有一个问题的理解在拉威尔雄辩。 mysql中有4个表:

    enter image description here

    A类和B类的id是相同的。类A和类C的id是相同的。A类的标识符可以在表B或表C中。

    转化为模型ORM:

    class Utilisateurs extends Model
    {
        public function as()
        {
            return $this->hasMany(A::class);
        }
    }
    
    class A extends Model
    {
        public function utilisateur()
        {
            return $this->belongsTo(utilisateur::class);
        }
    
        public function b()
        {
            return $this->hasOne(B::class);
        }
    
        public function c()
        {
            return $this->hasOne(C::class);
        }
    }
    
    class B extends Model
    {
        public function A()
        {
            return $this->belongsTo(A::class);
        }
    }
    
    class C extends Model
    {
        public function A()
        {
            return $this->belongsTo(A::class);
        }
    }
    

    我知道一个办法。

    public function getB(int $id)
    {
        $user = Utilisateur::find($id);
        $bs = array();
        if($user){
            $user->a()-each(function($item){
                $b = $item->b()->first();
                if($b){$bs[] = $b}
            })
        }
        return $bs;
    }
    

    谢谢。

    帖子解决了:最好的方法是利用关系: Has Many Through

    3 回复  |  直到 7 年前
        1
  •  1
  •   Vivick    7 年前

    hasManyThrough .

    否则,你可以用拉威尔的 Collection methods 具体如下:

    $user = Utilisateurs::find($id);
    $bs = $user->as()->map(function($a){
      return $a->b()->first();
    })->filter(function($b){
      return $b;
    })->toArray();
    
        2
  •  0
  •   Gammer    7 年前
    $utilisateur = Utilisateur::findorFail(id);
    // Each and every B which belongs to the utilisateur.
    $bs = $utilisateur->as->map->b;
    // Each and every C which belongs to the utilisateur.
    $cs = $utilisateur->as->map->c
    

    这样就行了。

        3
  •  0
  •   Tharaka Dilshan    7 年前
    $utilisateur = Utilisateur::find(id);
    
    // all the b models which belongs to the utilisateur.
    $bs = $utilisateur->as->map->b;
    
    // all the c models which belongs to the utilisateur.
    $cs = $utilisateur->as->map->c
    

    $bs $cs 是集合,不是单一的模型。

    使用 optional() as

    $bs = optional($utilisateur->as)->map->b;
    
    推荐文章