laravel eloquent multiple record hasMany - laravel

return Store::whereRaw('status = 1 AND ' . 'pay_status = 1 AND ' . $conditions[0])
->storeBooks()
->whereRaw('status = 1 AND ' . $conditions[1])
->search($request->input('search'), null, true)
->simplePaginate(20)
->makeHidden(['description', 'publisher', 'edition', 'mobile', 'cat_title', 'city_name']);
Hi, I have an store table and this table has some book in store_books table.
i want to search in store books where store has status 1.
I wrote above code but not work.
anyone can help me? Please!
Thanks

You can try this
In your Store model
public function books()
{
return $this->hasMany("App\StoreBooks",'store_id');
}
In your controller's function
$results = [];
$stores = Store::where('status',1)->get();
foreach($stores as $store)
{
$books = $stores->books;
foreach($books as $book)
{
$results[] = $book;
}
}
return $results;

Related

Laravel Voyager Scope query returning all rows

I'm using laravel voyager with laravel 9 and I have an issue with the scope, the code is as follows:
public function scopeUser($query)
{ $products = DB::table('products')->select('id')->where('stakeholders_id', auth()->user()->id);
// dd($products);
$table = DB::table('product_variations')->whereIn('product_id',$products);
// dd($table);
return $table;
}
when I dd the $table variable I get the correct values needed when I add ->get() at the end but when I remove both I get all the rows in the database when I need only the authenticated user's product variations, any ideas??
tray this
public function scopeUser($query)
{
$products = Product::where('stakeholders_id', auth()->id());
if (count($products) > 0) {
if (count($products) > 1) {
$pluckIds = $products->pluck('id')->toArray();
$table = DB::table('product_variations')->whereIn('product_id', $pluckIds)->get();
return $table;
}else{
$pluckIds = $products->first()->id;
$table = DB::table('product_variations')->where('product_id', $pluckIds)->get();
return $table;
}
}else{
return false;
}
}

Running same query in 2 different views: What's the proper way?

Just getting started into laravel and need to run the same db query for 2 different views, I know I could just create 2 controllers and perform the same query in both passing it to each view.
But, is that the proper way? Or is there a way without repeating my code?
Thanks!
Edit:
I have the following function inside a controller:
protected function getLocation($url)
{
$match = ['url' => $url];
$location = DB::table('location')->where($match)->first();
if (!$location) {
abort(404);
}
return $location;
}
the controller is returning that data to a view:
public function showsubcatandlocation($service)
{
$category = $this->getCat($service);
$location = $this->getLocation($category);
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);
}
What's the proper way to reuse the getLocation function? Or should I just copy it in the new controller? I just need to use it in those 2 views.
maybe scope Query helps?
class Location extends Model
{
public function scopeMatch($query, $url)
{
return $query->where('url', $url);
}
}
And then your two controllel methods will be
$location = Task::match($url)->first();
if (!$location) {
abort(404);
}
return $location;
$category = $this->getCat($service);
$location = Task::match($category['url'])->first();
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);

Laravel 5.6 Many To Many Polymorphic Relations Insert Not Work

I'm use laravel 5.6 on this project. Categories value not recorded 'categorizables' pivot table. I check with f12 or bug but I do not get any errors. all of them ok but not recorded pivot table. Where I have
been mistake.
My Blog project sql structure is below
--blogs
id
title
description
...
-- categorizables
category_id
categorizable_id
categorizable_type
Below code belong to Category.php Model
class Category extends Model
{
protected $primaryKey='category_id';
public function blogs(){
return $this->morphedByMany('App\Blog', 'categorizable', 'categorizables', 'category_id');
}
}
Above code belong to Blog.php
public function category($categories)
{
$categories = Blog::buildCatArray($categories);
foreach ($categories as $catName) {
$this->addOneCat($catName);
$this->load('categories');
}
return $this;
}
public function buildCatArray($categories): array
{
if (is_array($categories)) {
$array = $categories;
} elseif ($categories instanceof BaseCollection) {
$array = $this->buildCatArray($categories->all());
} elseif (is_string($categories)) {
$array = preg_split(
'#[' . preg_quote(',;', '#') . ']#',
$categories,
null,
PREG_SPLIT_NO_EMPTY
);
} else {
throw new \ErrorException(
__CLASS__ . '::' . __METHOD__ . ' expects parameter 1 to be string, array or Collection; ' .
gettype($categories) . ' given'
);
}
return array_filter(
array_map('trim', $array)
);
}
protected function addOneCat(string $catName)
{
$cat = Self::findOrCreate($catName);
$catKey = $cat->getKey();
if (!$this->cats->contains($catKey)) {
$this->categories()->attach($catKey);
}
}
public function find(string $catName)
{
return $this->Category::$catName->first();
}
public function findOrCreate(string $catName): Category
{
$cat = $this->find($catName);
if (!$cat) {
$cat = $this->Category::create(['name' => $catName]);
}
return $cat;
}
This my Blog Controller file store class
BlogController.php
public function store(Request $request)
{
$data = new Blog;
$data->title = $request->title;
$data->content = $request->content;
$tags = explode(',',$request->tag);
$categories = explode(',',$request->category);
$data->save();
$data->tag($tags);
$data->category($categories);
}
Best wishes

I need help Select Sum in codeigniter

I need help to help me correct my php function in codeigniter.
I have a database; I want addirionner all values ​of " from_user_id ".
Check data
I use this sql to get the desired result.
SELECT SUM(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) AS total_stats FROM score WHERE from_user_id = ?
In codeingniter I​ use this function.
It allows me to check if " from_user_id " exists, if it exists, we calculate the total different tables and we update the result in " total_stats ". If " from_user_id " does not exist, create it.
But my function does not return me the right result.
I had to make a big mistake but I do not know where!
Does someone could help me please.
public function count_tout_stats($user_id) //total des stats
{
$this->db->select_sum(conv_recu, conv_envoi, repon_topic, etc...);
$query = $this->db->from('score');
$this->db->where('from_user_id', $user_id);
$total_stats = $this->db->count_all_results();
if ($this->ttl_stats_score($user_id) > 0) // Check if exists
{
$data = array(
'total_stats' => $total_stats
);
$this->db->where('from_user_id', $user_id);
$this->db->update('score', $data);
}
else
{
$data = array(
'from_user_id' => $user_id,
'total_stats' => $total_stats
);
$this->db->insert('score', $data);
}
return $total_stats;
}
public function ttl_stats_score($user_id)
{
$this->db->where('from_user_id', $user_id);
$this->db->from('score');
return $this->db->count_all_results();
}
Thank you in advance for your assistance
Violette
You can try this:
$this->db->select('(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) as total_stats');
$this->db->from('score');
$this->db->where('from_user_id', $user_id);
$result = $this->db->get()->row_array();
print_r($result);
You will get your result

Laravel 5.1 Command empty table

I'm using a command to add products from an API to my database using the following code
class UpdateCatalog extends Command {
protected $name = 'catalog:update';
protected $description = 'Command description.';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$products = Api::productsGetProducts();
foreach($products as $product)
{
$detail = Api::productsGetProduct($product['id']);
$product = new Product();
$product->id = $detail->getId();
$product->external_id = $detail->getExternalId();
$product->name = $detail->getName();
$product->description = $detail->getDescription();
$product->thumbnail = $detail->getThumbnail();
$product->price = $detail->getPrices()[0]['price_excl_vat'];
$product->vat = $detail->getVat();
$product->save();
}
}
}
Now I'm wondering if it's possible to empty the table prior to filling it again.
Thank you!
Do you mean you want to empty your Product database table?
This can be done with truncate like this:
Product::truncate();
Note: This will remove all rows and reset the auto-incrementing ID to zero

Resources