Hi Guys,
So firstly here is some code ...
So I have a user model, and that user model has a relation to a 'Profile' model (one-to-one), however there are two types of profile, either a Consultant or a Customer so for that reason I have used a Polymorphic relationship.
This seems to work fine, however in one of my repositories I need to be able to fetch all the users who have a certain speciality listed in their Consultant Profile.
I have been trying to use whereHas on the polymorphic relationship, but this doesn't seem to work, the error message I get back is as follows :-
"Illuminate \ Database \ QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.' in 'where clause' (SQL: select * from users
where (select count(*) from users
where users
.profile_id
= users
.`` and speciality
LIKE %anth%) >= 1)"
I have a feeling I am missing something obvious, but its really odd since the relationship seems to work fine, just not the query I am trying todo.
Thanks,
Rich
whereHas
can't do it as it doesn't know what tables it should check. In fact polymorphic relations have some bugs, because of null
passed to the constructor for example, that make morphTo
unable to use some of the builder methods. You can't eager load such relation with additional constraints passed as a closure in with
method and so on.
So basically you can query the other tables and eager load User for the results as a workaround
Thanks for the reply, I had a feeling that this was the case ... I did think about going at the data from the other tables, but that does seem a little weird, but as you say .. its a work around..
thanks for the help! :)
Hi,
Can I ask how your DB schema looks like for morphOne()?
I'm not sure how this is suppose to work.
In my case I have an orders
table which has an address_id
foreign key to the addresses
table. But I also have an organisations
table that also contains an address_id
foreign key.
Are these the only requirements to make morphOne() relationship work?
Further I shouldn't have hasOne()
and belongsTo()
if I'm using morphOne()
correct?
UPDATE: I think I get it now. I missed a section in the docs that explained this.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community