Yêu cầu thg 4 11, 2019 8:51 SA 222 1 2
  • 222 1 2
0

Em xin hỏi về vấn đề Many To Many (Polymorphic) trong Laravel với ạ !!!

Chia sẻ
  • 222 1 2

Em có 3 table như sau

user
    id
    name
    ...
cities
    id
    name
multi_cities
    id
    city_id
    model_type
    model_id

Em thực hiện code liên kết các bảng như sau ạ

class User extends Authenticatable
{
    use Notifiable;
    public function cities()
    {
        return $this->morphToMany('App\City', 'model');
    }
}
class City extends Model
{
    protected $table = 'cities';
    protected $fillable = ['name'];
    public function users() {
        return $this->morphedByMany('App\User', 'model');
    }

    public function jobs() {
        return $this->morphedByMany('App\Job', 'model');
    }
}
class MultiCity extends Model
{
    protected $table = 'multi_cities';
    protected $fillable = ['city_id', 'model_type', 'model_id'];
}

Em thử query trong route như sau:

Route::get('/user', function () {
    $user = App\User::find(3);
    foreach ($user->cities as $city) {
        echo $city . '<br>';
    }
});

Báo lỗi không tìm thấy table tương ứng với model Bác nào thông não e với 😃)

2 CÂU TRẢ LỜI


Đã trả lời thg 4 11, 2019 9:34 SA
Đã được chấp nhận
+3

nó đang báo lỗi bảng job_here.models không tồn tại kìa bạn.

Chia sẻ
thg 4 12, 2019 6:53 SA
    public function cities()
    {
        return $this->morphToMany('App\City', 'model', 'multi_cities');
    }

Thử xem được ko nhé.

Avatar duongricky @duongricky
thg 4 13, 2019 3:51 SA

@tiennguyen98 dạ được rồi a, e cảm ơn

Đã trả lời thg 4 12, 2019 1:39 SA
+2

thay

public function cities()
    {
        return $this->morphToMany('App\City', 'model');
    }
}

bằng

public function cities()
    {
        return $this->morphToMany('App\City', 'multi_cities');
    }
}

tương tự với morphedByMany. Check docs nhá bạn: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many-polymorphic-relations :v

Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí