I've been trying to wrap my head on figuring out how to update my hasMany relationship model. I can easily create new relationships but when I try to update my relationship model it does not work? Does laravel push() method still work? Can anyone help please? For example I want to update my Taxonomy Table thats related to my Products table within my Controller. I have a code snippet below::
Product.php
class Product extends Model
{
protected $fillable = [
'product_category', 'product_subcategory', 'product_name',
'product_price', 'product_id', 'product_description', 'product_image'
];
protected $primaryKey = 'product_id';
public $incrementing = false;
public function addTaxonomiesToProduct()
{
return $this->hasOne('App\Taxonomies', 'product_id', 'product_id');
}
}
Taxonomies.php
class Taxonomies extends Model
{
protected $fillable = ['product_category', 'product_subcategory'];
protected $primaryKey = 'product_id'; // or null
public $incrementing = false;
public function product()
{
return $this->belongsTo(Product::class);
}
}
EditProductController.php
class EditProductController extends Controller
{
public function update(Request $request, Product $product)
{
$product_size = array();
foreach ($request->product_size as $key => $value)
{
array_push($product_size,$value);
}
$product->update([
'product_name' => $request->product_name,
'product_price' => $request->product_price,
'product_description' => $request->product_description,
'product_size' => serialize($product_size),
'product_image' => $product_image_path,
]);
/**
* Go the products table,
* Get the product based off its product_id,
* and then update this products taxonomy
**/
$taxonomies = Product::find($product->product_id);
$taxonomies->addTaxonomiesToProduct->product_subcategory = "Mens Shoes";
$taxonomies->push();
}
}
****Update Issued Solved****
By changing hasMany() to hasOne() within my Products table, my taxonomies table updated correctly.
I think you don't fully understand the way Laravel Eloquent relationships work. First off, you need to define the relationship in both models.. Your Taxonomy model has this, but your Product model should have:
public function taxonomies()
{
return $this->hasMany('App\Taxonomies', 'product_id', 'product_id');
}
Then to update a Product's taxonomies, you'd have something like...Uh, I'm not sure what you're trying to achieve here, especially with the way you chained the product_subcategory, so I can't rightly say, but do see the documentation
Related
Hello I have a question:
I have three things :
Top Category
Category
Product
I want to have this : Top Category -> Category -> Product
So I can get all nested information to one Top Category
My Models :
class Overcategory extends Model
{
use HasFactory;
protected $fillable = [
'name',
'img',
];
public function categories()
{
return $this->belongstoMany(Category::class);
}
}
class Category extends Model
{
use HasFactory;
protected $fillable = [
'category_title',
'category_description',
'category_preview_img',
'over_categories_id',
'order',
'price'
];
public function product()
{
return $this->belongstoMany(Product::class);
}
public function overcategories()
{
return $this->belongstoMany(Overcategory::class);
}
}
class Product extends Model
{
use HasFactory;
protected $fillable = [
'product_title',
'product_desc',
'product_preview_img',
'product_price',
];
public function category()
{
return $this->belongstoMany(Category::class);
}
}
And my code to get the Top Category with Category is this :
$relationsship = Overcategory::with('categories')->get();
How would I get the categories with their product too?
In order to get all Overcategory with their Category and their Product, you can use the dot notation when you eager load the relationships.
$relationsship = Overcategory::with('categories.product')->get();
// will get you all the Overcategories with a Categories relationshiop and inside each Category, the Products will be loaded.
This also works the exact same way when you are working on eloquent collections instead of a query builder, with the load method instead of with.
If you want to read more on this topic, here is the documentation https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence.
Quick note aside, if a relationship returns multiple items (which is the case with product) it should be plural (products).
My Post model has this function not working
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = "wp_posts";
protected $primaryKey = "ID";
public function taxonomies()
{
return $this->belongsToMany('App\Models\TermTaxonomy', 'wp_term_relationships', 'object_id', 'term_taxonomy_id');
}
}
I wanna get the taxonomies data from post through pivot table but I can't.
I connected Laravel to my WP database and tried to get Taxonomies from Posts.
Posts and Taxonomies are many to many relationship with 'wp_term_relationships' pivot table.
post table has 'ID' primary key
taxonomy table has 'term_taxonomy_id' primary key
The pivot table is like
'wp_term_relationships'
- 'object_id' ... related to Post.ID
- 'term_taxonomy_id' ... related to Taxonomy.term_taxonomy_id
I don't know why this not working. If anyone knows plz help me. Thank you so much.
Add
// Taxonomy
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TermTaxonomy extends Model
{
protected $table = 'wp_term_taxonomy';
protected $primaryKey = 'term_taxonomy_id';
}
// in the Controller
public function profile($id)
{
$teacher = User::isTeacher()->where(['ID' => $id])->with(['posts' => function ($query) {
$query->where('post_type', 'answer')->take(3);
}])->firstOrFail();
$data = [
'teacher' => $teacher
];
return view('teacher.profile', $data);
}
// in the View
#foreach($teacher->posts as $answer)
#php
foreach($answer->postParent->taxonomies as $taxonomy) {
print($taxonomy->term_id);
}
#endphp
#endforeach
The actual problem was not how to define many to many relationship,
it was how to retreive the relation data.
public function profile($id)
{
$teacher = User::isTeacher()->where(['ID' => $id])->with(['posts' => function ($query) {
$query->where('post_type', 'answer')->take(3)->with(['postParent' => function ($query) {
$query->where('post_type', 'question')->with(['taxonomies' => function ($query) {
$query->where('taxonomy', 'question_category')->with(['term']);
}]);
}]);
}])->firstOrFail();
$data = [
'teacher' => $teacher
];
return view('teacher.profile', $data);
}
I have Three models:
Language
Article
Category
The Article table has two foreign keys category_id and Language_id. Language-Model has "One to Many" Relationship with Article-Model, Similarly Category-Model has "One to Many" Relationship with Article-Model.
My Category model:
class Category extends Model
{
protected $fillable = [
'category_name',
];
public function articles(){
return $this->hasMany('App\Article');
}
}
My Language model:
class Language extends Model
{
protected $fillable = [
'language_name'
];
public function articles(){
return $this->hasMany('App\Article');
}
}
My Article model:
class Article extends Model
{
protected $fillable = [
'language_id','category_id','category_name','article_title',
'article_desc','source_from','source_url','video_link',
'audio_url','author_name','article_image_url','like_count'
];
public function languages(){
return $this->belongsTo('App\Language');
}
public function categories(){
return $this->belongsTo('App\Category');
}
}
How can I insert in the database using Laravel Eloquent?
$Article = new Article (
[
'article_image_url' => $img_url ,
'audio_url' => $audio_url,
'category_name'=>$category_name ,
'article_title'=>$request->article_title,
'article_desc'=>$request->article_desc,
'source_from'=>$request->source_from,
'source_url'=>$request->source_url,
'video_link'=>$request->video_link,
'author_name'=>$request->author_name,
'like_count'=>'0',
]
);
$language = new Language;
$category = new Category;
$language->articles()->save($Article);
language_id doesn't have a default value; it is foreign key.
TL;DR
Trying to get three models to interact using eloquent for a rest api.
User - belongsToMany(pulls)
Pull - belongsToMany(user) && belongsToMany(boxes)
Box - belongsToMany(pulls)
The pull_user table is working perfectly, I can just attach a user after I save a pull. Saving a box works fine but the attach doesn't work/enter anything into the pivot table (I get no errors though).
The Problem
I can't get a pivot table that associates two of my models together to attach() after a save. I have the three models listed above, the pivot is working for pull_user but not for pull_box even though the save for box is working perfectly. I am able to save a box without an error but the association just never occurs (no error).
The Code
pull_box.php
class PullBox extends Migration
{
public function up()
{
Schema::create('pull_box', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('pull_id');
$table->integer('box_id');
});
}
public function down()
{
Schema::dropIfExists('pull_box');
}
}
Pull.php
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box');
}
}
Box.php
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull');
}
}
BoxController.php
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
...
]);
$user_id = $request->input('user_id');
...
$box = new Box([
'user_id' => $user_id,
...
]);
$pull = Pull::whereId($pull_id)->first();
if($box->save()){
$pull->boxes()->attach($box->id);
$box->view_box = [
'href' => 'api/v1/box/' . $box->id,
'method' => 'GET'
];
$message = [
'msg' => 'Box created',
'box' => $box,
'pull' => $pull_id
];
return response()->json($message, 201);
}
$response = [
'msg' => 'Box creation error, contact supervisor',
];
return response()->json($response, 404);
}
The Solution
I need to know how I can get this association working. I am going to need to add a new layer in under the pull for Item, but I don't want to move one before I solve this. I think that my problem has to stem from a syntactical/logical error on my part but I can't see it. There are a bunch of questions on SO that are very close to giving me a solution, but after reading them I wasn't able to solve my problem.
Any help is appreciated.
Try renaming your pull_box table to box_pull, pivot tables on laravel must be in alphabetical order. If you want to use custom name on pivot table you have to extends your pivot, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PullBox extends Pivot
{
protected $table = 'pull_box';
}
And your many to many relationships:
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box')->using('App\PullBox');
}
}
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull')->using('App\PullBox');
}
}
I've got MySQL tables for site cart:
Cart:
id | user
Cart_goods:
cart_id | good_id | good_type
Details:
id | name
Appliances:
id | name
Class Cart, which contains goods:
class Cart extends Model
{
protected $table = 'cart';
protected $fillable = ['user', 'sum', 'profit', 'discount'];
protected $guarded = ['user'];
public function goods()
{
return $this->hasMany('App\Models\Good');
}
}
Class Good, which can be Detail or Appliance and relative to cart by cart_id:
class Good extends Model
{
protected $table = 'cart_goods';
protected $types = [
'Detail' => 'App\Models\Detail',
'Appliance' => 'App\Models\Appliance'
];
public $primaryKey = 'cart_id';
public function good()
{
return $this->morphTo();
}
}
Detail class:
class Detail extends Model {
use SoftDeletes;
protected $morphClass = 'Detail';
protected $table = 'details';
protected $fillable = ['article', 'name', 'photo', 'price_procurement', 'price_retail', 'serial', 'location_id', 'type_id', 'appliance_id', 'comment', 'for'];
protected $dates = ['deleted_at'];
protected $guarded = [];
public function goods()
{
return $this->morphMany('App\Models\Good', 'good');
}
}
And i need to get all appliances and details in cart. How can i do it by using ORM?
Use nested eager loading. Assuming that relationship method names are cartGoods, details and appliances, that details are details of a cart and that you've defined the relationships right:
Card::where('id', $id)
->with('cartGoods.appliances', 'details')
->first();
Try this:
Method 1: If you have a $cart model instance
$cart->load('goods.good');
Method 2: If you need all appliances and details from cart by card ID
Cart::where('id', $cartId)->with('goods.good')->first();
I've done this, problem was in model name, i was writing it to DB like Detail and Appliance, but i was need to use
Relation::morphMap([
'detail' => 'App\Models\Detail',
'appliance' => 'App\Models\Appliance',
]);
In AppServiceProvider class.