Reputation: 676
I have table, 'jobs', indexed by job_id, and and table discussions with foreign key 'job_id'.
In jobs I have a column called 'summary', and in discussions a column called 'body'. I want to search for the same text string in both of these columns across both these tables and return the applicable jobs.
Eg, if a jobs record with job_id=7 has the string 'somestring' in it's 'summary' column, and a discussions record has foreign key job_id=20 and has string 'somestring', I want the job records for job_id=7 and job_id=20 returned.
I am using laravel. I'm having trouble finding a solution, this is the closest I have got:
$query->join('discussions', function( $join ) use ( $search_term ){
$join->on('jobs.job_id', '=', 'discussions.job_id');
$join->where('discussions.body', 'LIKE', $search_term );
$join->orWhere('jobs.summary', 'LIKE', $search_term );
})
But this just returns everything from my discussions table. Does anyone have any suggestions?
Thanks :)
Upvotes: 0
Views: 1209
Reputation: 81187
There's SQL problem with that. What you are doing is basically this:
SELECT * FROM jobs INNER JOIN discussions ON (...) jobs.summary LIKE search_term
There is no WHERE
clause, and that part (...)
doesn't matter (simplified a bit) since there is OR
, so in fact you don't (not only) join the table on the key/fk pair.
You simply need to move those where
s out of the join closure and it will work as expected:
$query->join('discussions', function( $join ) {
$join->on('jobs.job_id', '=', 'discussions.job_id');
})
->where('discussions.body', 'LIKE', $search_term )
->orWhere('jobs.summary', 'LIKE', $search_term )
->get();
Now your query will look like it should:
SELECT * FROM jobs INNER JOIN discussions ON jobs.id = discussions.job_id
WHERE discussions.body LIKE search_term
OR jobs.summary LIKE search_term
Upvotes: 1
Reputation: 2647
Try this and see what comes out of it ;)
$query->join('discussions', function( $join ) use ( $search_term ){
$join->on('jobs.job_id', '=', 'discussions.job_id')
->where('discussions.body', 'LIKE', $search_term )
->orWhere('jobs.summary', 'LIKE', $search_term );
})
->select('*')
->get();
EDIT: I would replace the $query
with the correct DB::table('mytable')
.
DB::table('jobs')->join('discussions', function( $join ) use ( $search_term ){
$join->on('jobs.job_id', '=', 'discussions.job_id')
->where('discussions.body', 'LIKE', $search_term )
->orWhere('jobs.summary', 'LIKE', $search_term );
})
->select('*')
->get();
EDIT2: I missed a semicolumn, corrected
Upvotes: 0