3

I want to change this MySQL query to Larvel Grammar.

MySql inner Join

 select u.name , c.title , c.content 
 from users u 
 inner join communities  c on u.id = c.user_id
 where u.name like '%name%'

4 Answers 4

2

Try this query:

DB::table('users')
     ->select(['users.name', 'communities.title', 'communities.content'])
     ->join('communities', 'communities.user_id', '=', 'users.id')
     ->where('users.name', 'like', '%' . $request->name . '%')
     ->get();
Sign up to request clarification or add additional context in comments.

Comments

2

Dont know what do you mean by Larvel Grammar. but i think you thinking about laravel eloquent or query builder:

Your query:

 select u.name , c.title , c.content 
 from users u 
 inner join communities  c on u.id = c.user_id
 where u.name like '%name%'

Query Builder:

 DB::table('users')
     ->select(['name', 'c.title', 'c.content'])
     ->join('communities as c', 'c.user_id', '=', 'users.id')
     ->where('name', 'like', '%' . $request->name . '%')
     ->get()

Eloquent (if you have those models):

User::with('communities')
        ->where('name', 'like', '%' . $request->name . '%')
        ->get();

Note: User model should have communities relation:

   public function communities(){
      return $this->hasMany(Community::class);
   }

Comments

0

You can use Laravel Query builder. Add use DB; at the top (in Class) of your controller.

Then use this, When you want to get data.

$users = DB::table('users')
                ->join('communities', 'users.id', '=', 'communities.user_id')
                ->select('users.name , communities.title , communities.content')
                ->where('users.name','LIKE','%name%')
                ->get();

1 Comment

public function searchWriter($search){ return DB::table('users') ->join('communities', 'users.id', '=', 'communities.user_id') ->select('users.name , communities.num,communities.country ,communities.title,communities.content,communities.hits,communities.commend,communities.created_at') ->where('users.name','LIKE',"%$search%") ->get(); } // An error is occurring. I'd like to get the results of my search as a writer.
0
DB::table('tableName')
->join('communities AS c','c.user_id','=','tableName.id')
->where('tableName.name','LIKE','name')
->select('tableName.name','c.title','c.content')
->get();

I hope this will help you. thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.